//页面间传值
//通过url传参
传值:
"/pages/test/test?item=..." (url有长度限制,太长的字符串会传递失败)
//例如要传值三方openid 和多个字符串时
// 可使用窗体通信、全局变量,或encodeURIComponent等多种方式解决,如下为encodeURIComponent示例。
'/pages/test/test?item='+ encodeURIComponent(JSON.stringify(item))
// 在test.vue页面接受参数
接收:
onLoad: function (option) {
//一般传值
const item = option.item
//encodeURIComponent示例
const item = JSON.parse(decodeURIComponent(option.item));
}
//窗体通信 (vue页面与nvue页面的通信传值)
// 发送信息的页面
// $emit(eventName, data)
uni.$emit('douyin', {
title: '我是title',
content: '我是content'
});
// 接收信息的页面
使用此页面通讯时注意事项:要在页面卸载前,使用 uni.$off 移除事件监听器
// $on(eventName, callback)
uni.$on('douyin', (data) => {
console.log('标题:' + data.title)
console.log('内容:' + data.content)
})
onUnload(){
// uni.$off('douyin')
destroyed() { //onUnload 里边 uni.$off 移除 //移除事件监听器
// uni.$off('douyin')//点击返回 将当前时间取消 防止下次点及出现累加
}
//或者一次性的事件,直接使用 uni.$once 监听
uni.$once('douyin',function(data){
//do something
//that.getCurrentClickVideo(data.id)
})
//全局通信 vuex
//nvue 不能使用外部变量eg:全局封装的api请求 ,但是nvue支持vuex 不支持直接引入store使用,可以使用mapState、mapGetters、mapMutations等辅助方法或者使用this.$store ,
//定义store
const store = new Vuex.Store({
state: {
login: false
},
mutations: {
login(state, provider) {
},
logout(state) {
state.login = false;
}
}
})
//然后,需要在 main.js 挂载 Vuex
//import store from './store'
//Vue.prototype.$store = store
//使用store
<script>
import {
mapState,
mapMutations
} from 'vuex';
export default {
computed: {
...mapState(['avatarUrl', 'login', 'userName'])
},
computed: mapState({
count: 'count', // 第一种写法
sex: (state) => state.sex, // 第二种写法
from: function (state) { // 用普通函数this指向vue实例,要注意
return this.str + ':' + state.from
},
// 注意下面的写法看起来和上面相同,事实上箭头函数的this指针并没有指向vue实例,因此不要滥用箭头函数
// from: (state) => this.str + ':' + state.from
myCmpted: function () {
// 这里不需要state,测试一下computed的原有用法
return '测试' + this.str
}
}),
methods: {
...mapMutations(['logout'])
}
}
</script>
//全局通信 全局变量globalData
//uni-app 在app.vue文件export default里面定义globalData,在当前文件(app.vue)里面获取globalData需要用this.$options.globalData获取,其他文件则用getApp().globalData获取。
globalData: {
text: 'text'
},
js中操作globalData的方式如下: getApp().globalData.text = 'test'