Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
本文将详细的介绍一下vuex在uni-app中使用教程
一、引入vuex,在项目根目录创建文件夹store,并创建文件index.js(uni-app已经内置了vuex,所以我们直接引入就可以了)
二、在/store/index.js文件中编写以下内容
//demo中的数据是模拟状态数据,用于测试,实际使用中,请根据您自己的业务编写
import Vue from ‘vue’
import Vuex from ‘vuex’
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
testArr:[‘123’,‘456’,‘789’],
count:0,
},
mutations: {
setCountInc(state,num){
state.count = num;
},
setTestArrInc(state,arr){
state.testArr = arr;
}
},
actions: {
},
getters:{
count(state,getters){
return state.count
},
testArr(state,getters){
return state.testArr
},
}
})
export default store
三、在入口文件main.js中挂载vuex
import Vue from ‘vue’
import App from ‘./App’
//引入vuex
import store from ‘./store’
//把vuex定义成全局组件
Vue.prototype.$store = store
Vue.config.productionTip = false
App.mpType = ‘app’
const app = new Vue({
…App,
//挂载
store
})
app.$mount()
四、在页面中使用
<.template>
<.view>
<.text>{{count}}<./text>
<.view v-for="(item,index) in testArr" :key=“index”>
<.text>{{item}}<./text>
<./view>
<.button type=“default” @click=“countChange”>点击count+1<./button>
<.button type=“default” @click=“testArrChange”>点击testArr+1<./button>
<./view>
<./template>
<.script>
import {mapGetters,mapMutations} from ‘vuex’
export default {
onLoad() {
console.log(this.$store)
},
//通过计算属性可以读取并实时监听状态的变化
computed: {
…mapGetters([‘count’]),
…mapGetters([‘testArr’]),
},
methods:{
…mapMutations([‘setCountInc’,‘setTestArrInc’]),
countChange(){
//通过Mutations里面的方法更新state状态
this.setCountInc(this.count + 1);
},
testArrChange(){
//通过Mutations里面的方法更新state状态
this.setTestArrInc(this.testArr.push(‘999’));
}
}
}
<./script>