更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。我们接着上一章的例子,我们想增加明星的名字,应该这样做:
在store的mutations里添加addStar方法
mutations: {
addStar(state){
state.stars.push({name:'李连杰',sex:'男'})
}
},
在A组件里通过this.$store.commit('addStar')来提交mutation,具体代码如下:
<template>
<div id="A">
<p>A组件</p>
<p>全部明星</p>
<p v-for="star in stars" :key="star.name">
{
{ star.name }}---{
{ star.sex }}
</p>
<button @click="addStar" style="color:black">添加明星</button>
</div>
</template>
<script>
import { mapState } from "vuex";
export default {
name: "A",
computed: mapState(["stars"]),
methods:{
addStar(){
this.$store.commit('addStar