创建
- 先在项目的根目录下创建store文件夹并在文件夹中创建index.js
- index.js中写上这些
import Vue from "vue"
import Vuex from "vuex"
Vue.use(Vuex);
export default new Vuex.Store({
state:{
},
mutations:{
}
})
- main.js中加上这两行
import store from './store'
Vue.prototype.$store = store
使用
index.js就相当于一个仓库
state中存放一些变量
mutations中存放方法
使用mutations中的方法
这是index.js中的一部分
export default new Vuex.Store({
state:{
model:""
},
mutations:{
setModel(state,phoneModel){
state.model = phoneModel
console.log(state.model)
}
}
})
setModel是我自己定义的一个方法
参数要有两个,第一个都是state(应该是指向上面的state吧,刚学的我还很懵逼),第二个是自己定义的参数
在app.vue中使用
export default {
onLaunch: function() {
console.log('App Launch');
let that = this;
uni.getSystemInfo({
success: function(res) {
that.$store.commit('setModel',res.model)
}
});
},
onShow: function() {
console.log('App Show');
},
onHide: function() {
console.log('App Hide');
}
};
</script>
使用这个方法只需要this.$store.commit('方法名',要传入的变量)
这里我传的是当前手机的型号
使用state中的值
使用非常简单
只需要this.$store.state.变量名
比如刚刚设好的model
this.$store.state.model