我正在使用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
函数中对数据状态进行更改,我该怎么做?
2条答案
按热度按时间ktecyv1j1#
很简单
字符串
但通常,如果你的一些状态依赖于其他一些状态,使用computed而不是watch可能是一个更好的主意:
型
Computed是懒惰的,缓存的,总体上更容易理解。手表的主要目的是执行副作用。
zvms9eto2#
在watch内部,您可以使用
this
关键字访问data
对象。要对data
对象进行更改,可以使用this.propertyName = newValue
进行更新。字符串
在此代码中,我们有一个名为
anotherState
的新数据状态,每当inputVal
发生更改时,它就会更新。我不确定我是否正确地理解了你的问题。你在找这个吗?