VueJs, difference between computed property and watcher?

前端 未结 6 1076
孤街浪徒
孤街浪徒 2020-12-09 01:24

On Vue.js documentation there is an example like below:

var vm = new Vue({
  el: \'#demo\',
  data: {
    firstName: \'Foo\',
    lastName: \'Bar\',
    full         


        
6条回答
  •  無奈伤痛
    2020-12-09 02:23

    You use a watcher when you want to mutate a value or perform an action based on some other value changing. A good example of this is when you set a value based on a prop and you want to react to any changes:

    Vue.component('my-comp',{
      template: '#my-comp',
      props: ['username'],
      created() {
        this.user = this.username;
      },
      watch:{
        username(val){
          this.user = val;
        }
      },
      data(){
        return{
          user: ''
        }
      }
    });
    

    See this JSFiddle: https://jsfiddle.net/fjdjq7a8/

    That example is a bit contrived and doesn't really work in the real world because we aren't syncing values, so here's a real example where I am using this in one of my open source projects:

    Computeds are for arbitrarily manipulating the data itself, so things like concatenating strings and calculating values.

提交回复
热议问题