美文网首页
Vue学习(2)计算属性和侦听器

Vue学习(2)计算属性和侦听器

作者: 好遠 | 来源:发表于2018-11-17 10:33 被阅读0次

一、计算属性(computed)

当模板中需要复杂的逻辑运算时,应当使用计算属性。

优点
便于维护。

#基础例子

<div id="example">
  <p>Original message: "{{ message }}"</p>
  <p>Computed reversed message: "{{ reversedMessage }}"</p>
</div>
var vm = new Vue({
  el: '#example',
  data: {
    message: 'Hello'
  },
  computed: {
    // 计算属性的 getter
    reversedMessage: function () {
      // `this` 指向 vm 实例
      return this.message.split('').reverse().join('')
    }
  }
})

结果:

Original message: "Hello"

Computed reversed message: "olleH"

这里reversedMesage作为message的gatter函数,当message改变时,reversedMessage也随之改变。

#计算属性 vs 方法

要实现复杂的逻辑运算,除了计算属性还可以使用方法。

computed:{
    reversedMessage:function(){
        return this.message.split('').reverse().join('');
    }
}
methods:{
    reversedMessage:function(){
        return this.message.split('').reverse().join('');
    }
}
<p>{{ reversedMessage }}</p>
<p>{{ reversedMessage }}</p>

两种方式的结果是一样的,区别是计算属性具有缓存,当依赖message不改变的时候,多次调用时是返回第一次的计算结果,只有依赖message改变时,才会重新求值。而方法是没有缓存的,每次调用都会重新求值。

#计算属性 vs 侦听属性

Vue提供一种通用的方式监控数据的变动:侦听属性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

一般默认使用的是计算属性的getter属性,但我们也可以自己提供一个setter:

computed:{
  fullname:{
    get:function(){
      return this.firstName + ' ' + this.lastName;
    },
    set:function(newVal){
      newVal  = newVal.split(' ');
      this.firstName = newVal[0];
      this.lastName = newVal[1];
    }
  }
}

二、侦听器

当需要在数据变化时执行异步或开销较大的操作时,这个方式是最有用的。

官方例子:

<div id="watch-example">
  <p>
    Ask a yes/no question:
    <input v-model="question">
  </p>
  <p>{{ answer }}</p>
</div>
<!-- 因为 AJAX 库和通用工具的生态已经相当丰富,Vue 核心代码没有重复 -->
<!-- 提供这些功能以保持精简。这也可以让你自由选择自己更熟悉的工具。 -->
<script src="https://cdn.jsdelivr.net/npm/axios@0.12.0/dist/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/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, oldQuestion) {
      this.answer = 'Waiting for you to stop typing...'
      this.debouncedGetAnswer()
    }
  },
  created: function () {
    // `_.debounce` 是一个通过 Lodash 限制操作频率的函数。
    // 在这个例子中,我们希望限制访问 yesno.wtf/api 的频率
    // AJAX 请求直到用户输入完毕才会发出。想要了解更多关于
    // `_.debounce` 函数 (及其近亲 `_.throttle`) 的知识,
    // 请参考:https://lodash.com/docs#debounce
    this.debouncedGetAnswer = _.debounce(this.getAnswer, 500)
  },
  methods: {
    getAnswer: 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
        })
    }
  }
})
</script>

额外知识
debounce
debounceFunc = _.debounce(func1, time)
“去抖函数”:当执行debounceFunc时,经过time的时间后才执行func1,若在time时间内再次执行debounceFunc,则重新计时time。

//简单实现debounce
var debounce = function(func, time){
  var last;
  return function(){
    _this = this;
    args = arguments;
    clearTimeout(last);
    var last = setTimeout(function(){
      func.apply(fthis, args);
      // apply(obj, args)
      // apply:调用一个对象(函数,这里是func),并用另一个对象(this)替换该对象
    }, idle)
  }
}

相关文章

网友评论

      本文标题:Vue学习(2)计算属性和侦听器

      本文链接:https://www.haomeiwen.com/subject/ucymfqtx.html