更改观察者中的观察者值

Sea*_*ean 10 vue.js vuejs2

我有一些类似于下面的代码:

<some_component v-model="some_value" />
{{ some_value }}
Run Code Online (Sandbox Code Playgroud)

在我的脚本代码中,我有以下内容:

 ...
 data() {
     return {
         some_value: 'initial'
     };
 },
 ...
 watch: {
     some_value(new_value, old_value) {
         // Small subset of code, actual code does much more than this
         if (new_value === 'some_new_value') {
              this.some_value = 'can not use that value';
         }
     }
 },
 ...
Run Code Online (Sandbox Code Playgroud)

因此,一切似乎都运行良好,直到我尝试更改从观察者本身内部观察的值。我希望观察者会再次触发,但它没有,并且虽然值发生了v-model变化,但它在用户界面中并没有改变。

我尝试this.$forceUpdate()在更改之前和之后使用,但似乎不起作用。

谁能告诉我我在这里做错了什么?

小智 10

你不应该更新你在观察者中观察的值,但如果你没有其他选择,你可以使用$nextTick

some_value(new_value, old_value) {
  // Small subset of code, actual code does much more than this
  if (new_value === 'some_new_value') {
    this.$nextTick(() => {
      this.some_value = 'can not use that value';
    })
  }
}
Run Code Online (Sandbox Code Playgroud)

另一种方法(我认为最好的方法)是直接覆盖v-model. 如您所知,v-model="some_value":value="some_value"和的简写@input="some_value=$event"。所以你可以做你想做的事情:

<some-component
  :value="some_value" 
  @input="some_value=some_method($event)"
/>
Run Code Online (Sandbox Code Playgroud)