一、在store 创建 home.js
const state = {
bookList: ["西游记", "水浒传", "红楼梦", "三国演义"],
num: 2
};
const getters = {
num: state => state.num * 2,
nums: state => state.num * 3
};
const mutations = {
SET_LIST: (state, list) => {
state.bookList = list;
}
};
const actions = {
//方式一
Action: (context, data) => {
context.commit("SET_LIST", data);
}
//方式二
// Action1({ commit }, data) {
// commit("SET_LIST", data);
// }
};
export default {
namespaced: true,
state,
getters,
mutations,
actions
};
二、页面使用
<template>
<div class="home">
{{bookList}}
<p>{{num}}</p>
<p>{{nums}}</p>
<button @click="handlePush()">点击变换</button>
</div>
</template>
<script>
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'
export default {
data () {
return {
list: ["哲学", "生活", "自律", "三体"]
}
},
computed: {
//方式一
// ...mapState({
// bookList: state => state.home.bookList
// }),
//方式二
...mapState("home", ["bookList"]),
//方式一
...mapGetters("home", ["num", "nums"]),
//方式二
// ...mapGetters("home", {
// num: "num",
// nums: "nums"
// })
},
methods: {
//方式一
// ...mapMutations({
// SET_LIST: "home/SET_LIST"
// }),
//方式二
...mapMutations("home", ["SET_LIST"]),
//方式一
// ...mapActions({
// Action: "home/Action"
// }),
//方式二
...mapActions("home", ["Action"]),
handlePush () {
// this.SET_LIST(this.list)
this.Action(this.list)
}
},
}
</script>