Person组件:
<template>
<div>
<h1>人员列表</h1>
<h3>Count组件求和为:{{ sum }}</h3>
<input type="text" placeholder="请输入名字" v-model="name" />
<button @click="add">添加</button>
<ul>
<li v-for="p in personList" :key="p.id">{{ p.name }}</li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
</template>
<script>
import { mapState } from "vuex";
import { nanoid } from "nanoid";
export default {
name: "Person",
data() {
return {
name: "",
};
},
computed: {
...mapState(["personList", "sum"]),
},
methods: {
add() {
const personObj = { id: nanoid(), name: this.name };
this.$store.commit("ADD_PERSON", personObj);
this.name = "";
},
},
};
</script>
<style>
</style>
Count组件
<template>
<div>
<h1>当前求和为:{{ sum }}</h1>
<h4>当前求和乘以10倍为:{{ bigSum }}</h4>
<h4>我在{{ school }},学{{ subject }}</h4>
<h3>Person组件的总人数是:{{ personList.length }}</h3>
<select v-model="n">
<!-- value默认是字符串类型,加上":"后 所有冒号里面的内容变成js表达式来解析-->
<!-- 或者使用 v-model.number="n" 强制类型转换-->
<option :value="1">1</option>
<option :value="2">2</option>
<option :value="3">3</option>
</select>
<!-- 要事先传递参数 -->
<button @click="increment(n)">+</button>
<button @click="decrement(n)">-</button>
<button @click="incrementOdd(n)">当前求和为奇数再加</button>
<button @click="incrementWait(n)">等一等再加</button>
</div>
</template>
<script>
import { mapState, mapGetters, mapMutations, mapActions } from "vuex";
export default {
name: "Count",
data() {
return {
n: 1, //用户选择的数字
};
},
methods: {
//借助mapMutations生成对应的方法,方法会调用commit去联系Mutations
...mapMutations({ increment: "JIA", decrement: "JIAN" }),
//借助mapActations生成对应的方法,方法会调用dispatch去联系actions
...mapActions({ incrementOdd: "jiaOdd", incrementWait: "jiaWait" }),
},
computed: {
//借助mapState生成计算属性,从state中读取数据(对象写法)
...mapState({
sum: "sum",
school: "school",
subject: "subject",
personList: "personList",
}),
//借助mapState生成计算属性,从state中读取数据(数组写法)
// ...mapState(['sum','school','subject'])
...mapGetters(["bigSum"]),
// bigSum() {
// return this.$store.getters.bigSum;
// },
},
};
</script>
<style>
button {
margin-left: 5px;
}
</style>