vue基础代码:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
wxj: {
name: 'wxj',
age: 10
},
zdz: '郑'
},
mutations: {
changeWxj(state, payload) {
state.wxj = payload.wxj;
},
changeZdz(state, payload) {
state.zdz = payload.zdz;
}
},
actions: {
changeWxj(store, payload) {
store.commit({
type: 'changeWxj',
wxj: payload
})
},
changeZdz(store, payload) {
store.commit({
type: 'changeZdz',
zdz: payload
})
}
},
getters: {
getWxj(state) {
return state.wxj;
},
getZdz(state) {
return state.zdz;
}
}
})
使用页面代码:
<!--这是一个vuex的基础教程-->
<template>
<div class="about">
<button @click="ceGet">获取数据</button> <br/>
<span>wxj数据:{{ this.wxjGet }}</span> <br/>
<span>zdz数据:{{ this.zdzGet }}</span> <br/>
<button @click="upSocket">改变数据</button> <br/>
<span>wxj数据:{{ this.wxjData }}</span> <br/>
<span>zdz数据:{{ this.zdzData }}</span> <br/>
<button @click="delayF">改变数据1</button> <br/>
<span>wxj1数据:{{ this.wxjData1 }}</span> <br/>
<span>zdz1数据:{{ this.zdzData1 }}</span> <br/>
</div>
</template>
<script>
import {mapGetters, mapActions} from 'vuex';
export default {
name: 'VX',
data () {
return {
wxjGet: {},
zdzGet: '',
wxjData: '',
zdzData: '',
wxjData1: '',
zdzData1: '',
skD: []
}
},
created() {
},
mounted(){
},
computed: {
...mapGetters([
'getWxj',
'getZdz'
])
},
methods: {
...mapActions([
'changeWxj'
]),
// 测试数据接口
ceGet() {
let a = this.getZdz;// 方法一
console.log(a);
this.zdzGet = a;
// console.log('你好VX', this.$store.getters.getWxj);
this.wxjGet = this.$store.getters.getWxj;// 方法二
console.log(this.wxjGet);
console.log('修改前', this.$store.state);
},
upSocket() {
console.log('问题', this.$store.state);// 问:为什么这里的打印是改变后的数据
let i = {
name: 'w',
age: 12
};
this.changeWxj(i);// 修改数据方法一
console.log('修改wxj', this.$store.state)
this.wxjData = this.$store.state.wxj;
this.$store.commit('changeZdz', { // 修改数据方法二
'zdz': 'zdz'
});
console.log('修改zdz', this.$store.state);
this.zdzData = this.$store.state.zdz;
},
delayF() {
console.log('问题', this.$store.state);// 问:为什么这里的打印是改变后的数据
let that = this;
setTimeout(function () {
let i = {
name: 'w1',
age: 121
};
that.changeWxj(i);// 修改数据方法一
console.log('修改wxj1', that.$store.state)
that.wxjData1 = that.$store.state.wxj;
that.$store.commit('changeZdz', { // 修改数据方法二
'zdz': 'zdz1'
});
console.log('修改zdz1', that.$store.state);
that.zdzData1 = that.$store.state.zdz;
},5000);
}
},
components: {
},
watch: {
}
}
</script>