vue.js - VueJs, difference between computed and watched properties? -
on vue.js documentation there example below:
var vm = new vue({ el: '#demo', data: { firstname: 'foo', lastname: 'bar', fullname: 'foo bar' }, watch: { firstname: function (val) { this.fullname = val + ' ' + this.lastname }, lastname: function (val) { this.fullname = this.firstname + ' ' + val } } })
the above code imperative , repetitive. compare computed property version:
var vm = new vue({ el: '#demo', data: { firstname: 'foo', lastname: 'bar' }, computed: { fullname: function () { return this.firstname + ' ' + this.lastname } } })
what situations when watchers more suitable computed properties? how should decide choose? documentation keeps saying more "generic" not put purpose.
computed properties
a computed property sample:
computed: { val () { return this.somedataproperty * someothervariable } }
what particular piece of code do?
it creates property named
val
component (on prototype<vueinstanece>.hasownproperty('val')
showfalse
).it has dependency tree consists of reactive properties (data properties, other computed properties) in case :
this.somedataproperty
, means moment dependencies change, computed property recalculated.although debated, can't have arguments passed it.
computed: { val (flag) { return (flag === 1) ? this.somedataproperty * someothervariable : this.somedataproperty * 5 } }
can't done
[edit] see: https://vuejs.org/v2/guide/computed.html#computed-setter
watcher
a watcher sample:
watch: { val (n, o) { console.log(n, o) } }
it not create new property, watches changes on reactive property.
watches 1 specific property, unlike computed dependent property change can cause recalculation.
has arguments of new , old value.
so computed properties way go if:
you want property depends on other properties always. text formatting template, example in code.
or reducing variable lengths quite common:
this.$store.state.someproperty.somenestedproperty.somedeeplynestedproperty
can reduced to:
computed: { somedeeplynestedproperty () { return this.$store.state.someproperty.somenestedproperty.somedeeplynestedproperty } }
not reduction in variable size, each time store updates, have latest value in somedeeplynestedproperty
.
and watchers useful if want see if 1 reactive property has changed favourable value know you're ready perform action.
like:
watch: { somethingselected() { this.router.push('someotherroute') } }
Comments
Post a Comment