vue中computed和watch的对比是一个很有意思的话题。
看过官网教程以后,我们往往更倾向多使用computed。computed优点很多,却在某些时候不太适用。
今天我们就稍微讨论一下,当我们在编写一个子组件时,需要同步父子组件的属性props时,computed与watch的选用。
举个例子好了。
首先看computed:
props: {
letter: {
type: String,
default: a
}
},
computed: {
innerLetter: {
get () {
return this.letter;
}
set (value) {
this.$emit('change-letter', value);
}
}
}
再来看看watch:
props: {
letter: {
type: String,
default: a
}
},
data () {
return {
innerLetter: this.letter
}
}
watch: {
letter (value) {
this.innerLetter = letter;
}
}
methods: {
changeLetter (value) {
this.$emit('change-letter', value);
}
}
两种写法要实现的功能都是要实现向子组件传入的props能够与父组件保持一致,这两种写法都很常见。
我们来看看他们的区别是什么:
computed写法,子组件的渲染依赖父组件对change-letter的响应,所以当编写强交互组件,或独立打包的外部plugin时,应谨慎使用或尽量不使用。
watch写法,在子组件仅read父组件的值,而不需要对其值进行修改时,完全可以用computed替代,computed性能更好,写法更简单。
ok,两种写法的区别你get到了么?
vue中computed(计算属性)和watch在实现父子组件props同步时的实际区分
原文:https://www.cnblogs.com/yinzhida/p/10673952.html