vue中使用vuex中的mutations修改state中的值了,但是在vue组件里this.$store.commit后computed不改变,书上的代码,通义的代码,豆包的代码都是一样的。可自己对着写的时候就是怎么样都没有效果
src\store\index.js的代码 如下 :
import {createStore} from 'vuex'
export default createStore({
state:{
name:'笔记本',
price: 7999
},
mutations:{
//涨价
addPrice(state,obj){
console.log("进入涨价方法",obj);
state.price += obj.num;
console.log("涨价后的值:",state.price);
},
//降价
subPrice(state,obj){
state.price -= obj.num;
}
},
actions:{},
modules:{}
})
src\components\HelloWorld.vue 的代码 如下 :
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<div>原来存在store里的name:{{ name }}, 价格:{{ price }}</div>
<div>
<button @click="aaa()">涨价</button>
<button @click="bbb()">降价</button>
</div>
</div>
</template>
<script>
import { mapState } from 'vuex';
export default {
name: 'HelloWorld',
data(){
return{
}
},
computed:{
...mapState(['name','price']),
},
methods:{
aaa(){
this.$store.commit('addPrice',{num:100})
console.log('执行完后state.price:',this.$store.state.price);
console.log('this.computed.price:',this.price);
},
bbb(){
this.$store.commit('subPrice',{num:100})
},
}
}
</script>
试过变成 state:{product:{name:'xxx',price:334}},然后改对象 里的值 ,结果 还是不行
解决了,就是版本的问题。晕。。AI给的代码根本没有标明是什么版本的。。同样的都是VUE3,能运行的是vue3.0.4, 不能运行的是vue3.2.13