uniapp的vue2版本使用vuex灵活存取数据
新建store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
count: 0,
clist:[1,2,3,4,6,6,7,8,9,0],
userInfo:"",
name:"xxq"
},
getters:{
count(state) {
return state.count;
},
name(state) {
return state.name;
},
userInfo(state) {
return state.userInfo;
},
clistgetters(state){
return state.clist.filter(function(item,index){return index<3})
}
},
mutations: {
increment (state) {
state.count++
},
chag (state,data) {
state.clist=data;
},
setUserInfo(state, userInfo) {
state.userInfo = userInfo;
},
chname (state,data) {
state.name=data;
},
},
actions: {
incrementAsync({ commit }) {
setTimeout(() => {
commit('increment');
}, 1000);
},
fetchUserInfo({ commit }) {
setTimeout(() => {
const userInfo = { name: 'Jane Doe', age: 26 };
commit('setUserInfo', userInfo);
}, 1500);
},
chaName({ commit },username) {
commit('chname', username);
}
}
})
export default store;
main.js
import Vue from 'vue'
import store from './store/store.js'
App.mpType = 'app'
const app = new Vue({
...App,
store
})
app.$mount()
页面中使用,index.vue
<template>
<view class="xBody">
首页
<text>当前计数:{{ count }}</text>
<button @click="increment">增加</button>
<button @click="incrementAsync">延迟增加</button>
<button @click="fetchUserInfo">获取用户信息</button>
<button @click="chagename">修改名称</button>
<view v-if="userInfo">
<text>用户信息{{ userInfo.name }},{{ userInfo.age }}岁</text>
</view>
<view>姓名:{{name}}</view>
<view>姓名2:{{membername}}</view>
</view>
</template>
<script>
var _this;
export default {
components: {},
data() {
return {
name:this.$store.getters.name
};
},
onLoad() {
_this = this;
},
filters: {},
computed: {
// 通过 Vuex 的 getters 获取状态(获取数据)
count() {
return this.$store.getters.count;
},
userInfo() {
return this.$store.getters.userInfo;
},
membername(){
return this.$store.getters.name;
}
},
methods: {
//调用方法改变存储的store的数据
increment() {
this.$store.commit('increment'); // 提交 mutation
},
incrementAsync() {
this.$store.dispatch('incrementAsync'); // 调用 action
},
fetchUserInfo() {
this.$store.dispatch('fetchUserInfo'); // 获取用户信息
},
chagename(){
this.$store.dispatch('chaName',"赵家辉");
}
},
};
</script>
<style lang="scss" scoped>
</style>

浙公网安备 33010602011771号