computed的set未执行

问题描述

computed的值改变了,但是他的set方法不会执行...

问题出现的环境背景及自己尝试过哪些方法

computed依赖于store, click修改store的值, 可以看到computed的值也相应做出改变,但是set方法没有触发,

相关代码

// 请把代码文本粘贴到下方(请勿用图片代替代码)

// store.js
export let state = Vue.observable({ testPlanId: '' })
export let mutations= {
    setTestPlanId(id){
        state.testPlanId = id
    }
}

//xxx.vue

<el-button @click="click">按钮</el-button>

 import {state,mutations} from './index'

  computed:{
           testPlanId:{
               get(){
                   return state.testPlanId
               },
               set(v){
                   console.log('撒大大')
                   this.page.query.planId = v
               }
           }
        },
        methods: {
         click(){
                console.log('click进来了')
                console.log('state.id', state.testPlanId)
                console.log('computed中tesrplanid',this.testPlanId)
                mutations.setTestPlanId('13141')
                console.log('-------------')
                console.log('state.id', state.testPlanId)
                console.log('computed中tesrplanid',this.testPlanId)
            },
        }
        
     

你期待的结果是什么?实际看到的错误信息又是什么?

题目描述

我认为的是vue中computed的set方法, 主要值发生变化就会触发,类似于watch,
那么当store的值发生改变,将触发computed的get方法,get方法将修改自身,
接下来自身的值发生变化(本例子是从''到'13141'),那么就应该触发set方法,打印'撒大大'
实际上set方法并未执行..
为什么?

clipboard.png

阅读 7.9k
3 个回答

store 里面的 testPlanId 和 computed 里的 testPlanId 并不是同一个对象,set 是定义 this.$data.testPlanId 的 setter 上的

你要直接修改 this.testPlanId 才会触发 set

你组件 里computed 的 testPlanId 只是 store 里面 testPlanId 的映射.你要触发组件里面 testPlanId 的set的话要给this.testPlanId 直接赋值才会触发set

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题