事件订阅
在APP.vue文件,写一个事件注册
onShow: function() {
uni.$on("testEvent",res=>{
console.log(res)
})
}
然后在index文件创建一个按钮触发这个事件
<!-- 创建button,点击触发事件 -->
<button type="default" @tap="testEvent">ok</button>
methods:{
testEvent(){
// name是传入的参数
uni.$emit("testEvent",{name:"mesa"})
}
}
参考链接:blog.csdn.net/weixin_4218…
使用globalData
globalConfig.js
export default {
data() {
return {}
},
computed: {
storeToken() {
return this.$store.state.token;
}
}
}
引入:
main.js
import globalConfig from './common/js/golbalConfig.js';
Vue.mixin(globalConfig);
页面调用:
export default {
data() {
return {};
},
watch: {
storeToken: function(nVal, oVal) {
if (nVal) {
// todo 其他操作
this.reload();
}
}
}
}
vuex
store.js内容如下:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
orderNumber: 0,
token: null
},
mutations: {
setOrderNumber(state, number) {
state.orderNumber = number
},
setToken(state, value) {
state.token = value;
},
},
actions: {
// 获取订单数
getOrderNumber() {
if (uni.getStorageSync("token")) {
// 接口获取
this.commit('setOrderNumber', 'xxx');
} else {
this.commit('setOrderNumber', 0);
}
}
}
})
export default store
引入:
import App from './App'
// 引入vuex
import store from './store'
// 把vuex定义成全局属性
Vue.prototype.$store = store
const app = new Vue({
...App,
store // 挂载store
})
页面调用:
mounted() {
this.$store.commit('setToken', 'xxxx);
this.$store.dispatch('getOrderNumber'); // 设置数量
},
// 计算属性 计算属性是基于它们的响应式依赖进行缓存的。只在相关响应式依赖发生改变时它们才会重新求值。
computed: {
// 获取数量
orderNumber() {
// todo 其他操作
// this.reload()
return this.$store.state.orderNumber;
}
}