Vue -从'watch'回调更改状态

m4pnthwp  于 2023-08-07  发布在  Vue.js
关注(0)|答案(2)|浏览(118)

我正在使用Vue,我已经看到你可以设置一个'watch'回调,用于当一段数据发生变化时:

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <input v-model="inputVal" placeholder="edit me" />
    <p>{{ inputVal }}</p>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  props: {
    msg: String
  },
  data() {
    return {
      inputVal: '22'
    }
  },

  watch: {
    inputVal: function(val, oldVal) {
      console.log('inputVal changed');
      console.log(oldVal);
      console.log(val);
    }
  }
}
</script>

字符串
如果我想在watch.inputVal函数中对数据状态进行更改,我该怎么做?

ktecyv1j

ktecyv1j1#

很简单

data() {
  return {
    inputVal: '22',
    isValueOdd: false
  }
},

watch: {
  inputVal(val, oldVal) {
    this.isValueOdd = val % 2 !== 0
  }
}

字符串
但通常,如果你的一些状态依赖于其他一些状态,使用computed而不是watch可能是一个更好的主意:

data() {
  return {
    inputVal: '22'
  }
},

computed: {
  isValueOdd() {
    return this.inputVal % 2 !== 0
  }
}


Computed是懒惰的,缓存的,总体上更容易理解。手表的主要目的是执行副作用。

zvms9eto

zvms9eto2#

在watch内部,您可以使用this关键字访问data对象。要对data对象进行更改,可以使用this.propertyName = newValue进行更新。

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <input v-model="inputVal" placeholder="edit me" />
    <p>{{ inputVal }}</p>
    <p>{{ anotherState }}</p>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  props: {
    msg: String,
  },
  data() {
    return {
      inputVal: '22',
      anotherState: 'Waiting for input',
    };
  },

  watch: {
    inputVal: function (val, oldVal) {
      console.log('inputVal changed');
      console.log(oldVal);
      console.log(val);
      this.anotherState = val + ' entered';
    },
  },
};
</script>

字符串
在此代码中,我们有一个名为anotherState的新数据状态,每当inputVal发生更改时,它就会更新。我不确定我是否正确地理解了你的问题。你在找这个吗?

相关问题