vue笔记--计算属性

来源:互联网 发布:德国工业发展数据分析 编辑:程序博客网 时间:2024/05/16 00:30

1.html

<div id="app">

<p>Original message:"{{message}}"</p>

</div>

2.script

var app = new Vue({

el:"#app",

data:{

message:'Hello!'

},

computed:{

reverseMessage:function(){

return this.message.split('').reverse().join('');

}

}

})




计算缓存vs method


我们可以通过调用表达式中的method来达到同样的效果
不经过计算属性,我们可以在method中定义一个相同的函数来替代它。对于最终的效果,
两种方式确实是相同的,然而,不同的是计算属性是基于它的一栏缓存。计算属性只有在
它的相关依赖发生变化时才会重新取值。这就意味着只要message没有发生改变,多次
访问reverseMessage计算属性会立即返回计算结果,而不必再次执行函数。
相比而言,每当重新渲染的时候,method调用总会执行函数。


计算缓存 vs watched property


vue.js提供了一个方法$watch,它对于vue实例上的数据变动。当一些数据需根据其他数据变化时,
$watch很诱人。不过通常更好的办法用计算属性而不是命令式的$watch回调
$watch:
<div id="demo">{{fullName}}</div>
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
    }
  }
})


计算属性
var vm = new Vue({
  el:'#demo',
  data:{
    firstName:'Foo',
    lastName:'Bar'
  },
  computed:{
    fullName:function(){
      return this.firstName+this.lastName
    }
  }
})


计算setter
computed:{
  fullName:{
    get:function(){
      return this.firstName+' '+lastName
    },
    set:function(newValue){
      var names = newValue.split(' ');
      this.firstName = names[0]
      this.lastName = names[names.length-1]
    }
  }
}
现在运行vm.fullname = 'John Doe'时,setter会被调用,vm.firstName和vm.lastName
也会被对应更新。




观察watchers


虽然计算属性在大多数情况下更合适,但有时也需要一个自定义的watcher。这是为什么Vue提供
一个更通用的方法通过watch选项,来响应数据变化。当你想要在数据变化响应时,执行一部操作
或开销较大的操作,这是很有用的。


<div id="watch-example">
  <p>
    Ask a yes/no question:
    <input v-model="question">
  </p>
  <p>{{answer}}</p>
</div>


script


var watchExampleVM = new Vue({
  el:'#watch-example',
  data:{
    question:'',
    anwser:'I cannot give you an answer until you ask a question!'
  },
  watch:{
    question:function(newQuestion){
      this.answer = 'waiting for you to stop typing...'
      this.getAnswer()
    }
  },
  methods:{
    getAnswer:_.debounce(
    function(){
      var vm = this
      if(this.question.indexOf('?')==-1){
        vm.answer = "questions usually contain a question mark"
        return
      }
      wm.answer = 'Think...'
      axios.get('https://yesno.wtf/api')
      .then(function(response){
        vm.answer = _.capitalize(response.data.answer)
      })
      .catch(function(error){
        vm.answer = "Error! Could not reach the API"+error
      })
    },
    500
    )
  }
})


0 0