uni-app中使用vuex

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>

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值