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?

  1. it creates property named val component (on prototype <vueinstanece>.hasownproperty('val') show false).

  2. it has dependency tree consists of reactive properties (data properties, other computed properties) in case : this.somedataproperty, means moment dependencies change, computed property recalculated.

  3. 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)    } } 
  1. it not create new property, watches changes on reactive property.

  2. watches 1 specific property, unlike computed dependent property change can cause recalculation.

  3. 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

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -