mapState、mapGetters:
vue文件完整代码:
<template>
<div class="about">
<button type="button" @click="handHome">Home</button> <br>
<button type="button" @click="handStoreList">List</button> <br>
<button type="button" @click="handAbout">About</button> <br>
Home: {{numHome ? numHome : 0}} <br><br>
List: {{list ? list : 0}} <br><br>
// mapState、mapGetter可以实时取到store中的值。
About,mapState: {{countState ? countState : 0}} <br>
About,mapGetter: {{countGetters ? countGetters : 0}} <br>
// 注:'count2'变量是定义在data中,通过this.$store.state.About.count,此种用法缺点是不能实时取到store中的值。
About,count2: {{count2 ? count2 : 0}} <br>
</div>
</template>
<script>
import { mapState, mapGetters } from "vuex";
export default {
data() {
return {
num: 88 + 'Home.vue',
about: {
age: 23,
type: 'Auout.vue'
},
listData: [{
name: 'List',
type: '存储数据'
}],
count2: this.$store.state.About.count,
}
},
methods: {
handHome(){
this.$store.commit('saveHomeNum',this.about)
},
handAbout(){
this.$store.commit("saveAboutCount",888);
console.log("About-count",this.count);
},
handStoreList(){
this.$store.commit('saveList',this.listData);
},
},
computed:{
...mapState({
numHome: state => state.List.numHome
}),
...mapState({
list: state => state.List.list
}),
...mapState({
countState: state => state.About.count
}),
...mapGetters(['countGetters']),
},
// computed: mapState((state) =>{
// })
}
</script>
<style>
button{
margin-bottom: 1rem;
height: 0;
}
</style>
store/index.js文件:
// store文件中,使用了modules模块化封装
import Vue from 'vue';
import Vuex from 'vuex';
import List from './modules/list.js';
import About from './modules/about.js';
Vue.use(Vuex)
export default new Vuex.Store({
state: {
data: {}
},
mutations: {
setData(state,val){
state.data = val;
}
},
actions: {
},
modules: {
},
// vuex模块化封装
modules:{
List,
About,
}
})
store/modules/about.js文件:
const state = {
count: 0,
}
const getters = {
countGetters: state =>{
return state.count;
}
}
const mutations = {
saveAboutCount(state,num){
state.count = state.count + num;
}
}
export default {
state,
getters,
mutations,
}
mapMutations:
vue文件完整代码:
<template>
<div class="list">
<button type="button" @click="saveA(618)">a: {{a}}</button>
</div>
</template>
<script>
import { mapGetters, mapMutations } from "vuex";
export default {
data() {
return {
a: this.$store.state.List.a
}
},
methods: {
...mapMutations(['saveA']), //点击按钮,触发这个mutations事件
},
mounted() {
console.log("a",this.a);
},
computed:{
// mapGetters: 监听list.js文件中 state.a的变化
...mapGetters([
'getListA'
])
},
watch: {
getListA: function(a){
this.a = a;
}
}
}
</script>
<style scoped>
</style>
store/modules/list.js文件:
const state = {
list: '',
numHome: '',
a: 666
}
const getters = {
getListA: state =>{
return state.a;
}
}
const mutations = {
saveHomeNum(state,val){
console.log("storeHome",val);
state.numHome = val;
},
saveList(state,val){
console.log("storeList",val);
state.list = val;
},
saveA(state,val){
state.a = state.a + val;
console.log("list_state.a",state.a);
}
}
export default {
state,
getters,
mutations
}