1、store文件夹代码
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
export default new Vuex.Store({
state() {
return {
connectId: 80,
connectIdB: 200,
};
},
mutations: {
setConnectId(state, n) {
state.connectId += n;
},
},
getters: {
//可认为是store的计算属性,若接收参数则返回一个函数
getAllId(state) {
return state.connectId + state.connectIdB;
},
//通过返回函数来给getters传参
getAllParams(state) {
return function (params) {
return state.connectId + state.connectIdB + params;
};
},
},
actions: {},
modules: {},
});
2、组件测试代码
<template>
<div class="home">
<el-button type="primary" @click="test">设置</el-button>
<el-button type="primary" @click="get">获取</el-button>
<el-button type="primary" @click="getStore">获取getters</el-button>
<!-- {{ getAllParams(100) }} -->
</div>
</template>
<script>
import { mapMutations, mapState, mapGetters } from "vuex";
export default {
name: "Home",
computed: {
// idValue() {
// return this.$store.state.connectId;
// },
//映射状态
...mapState({
idValue: "connectId",
}),
//映射store的计算属性
...mapGetters(["getAllId", "getAllParams"]),
},
methods: {
//映射修改状态的函数
...mapMutations({
Id: "setConnectId",
}),
test() {
this.Id(800);
},
get() {
//获取getter和状态的
alert(this.idValue);
alert(this.getAllId);
},
getStore() {
//getter实现传参
let s = this.getAllParams(100);
alert(s);
},
},
};
</script>
|