VUE计算属性

来源:互联网 发布:自建服务器绑定域名 编辑:程序博客网 时间:2024/06/05 02:51
    计算属性只能通过依赖值来改变;不能跟data一样进行改变,如果刚刚开始的时候需要依赖值计算;后来使用直接赋值进行改变,可以在另外一个计算属性中进行;    另外,子组件的data,不能在data中直接通过props传递过来的数据进行改变;必须通过计算属性来改变;

1:computed属性 VS methods属性

<div id="example">  <p>Original message: "{{ message }}"</p>  <p>Computed reversed message: "{{ reversedMessage }}"</p>  <p>Computed reversed message: "{{ reversedMessage1() }}"</p></div>var vm = new Vue({  el: '#example',  data: {    message: 'Hello'  },  methods: {  reversedMessage1: function () {    return this.message.split('').reverse().join('')  }},  computed: {    // a computed getter    reversedMessage: function () {      // `this` points to the vm instance      return this.message.split('').reverse().join('')    }  }})

我们发现将同一个函数定义为method,或者computed对于最终的结果确实是相同的,都会随着依赖值改变而改变。然而,不同的是计算属性是基于他们的依赖进行缓存的。
我们为什么需要缓存?假设我们有一个性能开销比较大的的计算属性 A ,它需要遍历一个极大的数组和做大量的计算。然后我们可能有其他的计算属性依赖于 A 。如果没有缓存,我们将不可避免的多次执行 A 的 getter!如果你不希望有缓存,请用 method 替代。

2:computed属性 VS watch属性

1:通常更好的想法是使用 computed 属性而不是命令式的 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    }  }})

上面watch属性中的代码是命令式,重复式的,下面的方法比较简单

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

2:计算属性的getter,setter

computed:{    fullName:{    //get为了将依赖值改变反应到到计算属性上        get:function(){            return this.first.name+' '+this.lastname        },    //set为了将计算属性改变反应到依赖值上           set:function(newValue){            var names=newValue.split(' ')            this.fistname=names[0]            this.lastname=names[names.length-1]        }    }}

现在再运行 vm.fullName = ‘John Doe’ 时, setter 会被调用, vm.firstName 和 vm.lastName 也相应地会被更新。
3:必须使用watch函数

<div id="watch-example">  <p>    Ask a yes/no question:    <input v-model="question">  </p>  <p>{{ answer }}</p></div>
<script src="https://unpkg.com/axios@0.12.0/dist/axios.min.js"></script><script src="https://unpkg.com/lodash@4.13.1/lodash.min.js"></script><script>var watchExampleVM = new Vue({  el: '#watch-example',  data: {    question: '',    answer: 'I cannot give you an answer until you ask a question!'  },  watch: {    // 如果 question 发生改变,这个函数就会运行    question: function (newQuestion) {      this.answer = 'Waiting for you to stop typing...'      this.getAnswer()    }  },  methods: {    // _.debounce 是一个通过 lodash 限制操作频率的函数。    // 在这个例子中,我们希望限制访问yesno.wtf/api的频率    // ajax请求直到用户输入完毕才会发出    // 学习更多关于 _.debounce function (and its cousin    // _.throttle), 参考: https://lodash.com/docs#debounce    getAnswer: _.debounce(      function () {        if (this.question.indexOf('?') === -1) {          this.answer = 'Questions usually contain a question mark. ;-)'          return        }        this.answer = 'Thinking...'        var vm = this        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    )  }})</script>

在这个示例中,使用 watch 选项允许我们执行异步操作(访问一个 API),限制我们执行该操作的频率,并在我们得到最终结果前,设置中间状态。这是计算属性无法做到的。