Vue.js 实战教程 V2.x(7)计算属性和侦听器

 图片

7计算属性和侦听器
7.1计算属性
模板内的表达式非常便利,但是设计它们的初衷是用于简单运算的。
 
在模板中放入太多的逻辑会让模板过重且难以维护。
 
所以,对于任何复杂逻辑,你都应当使用计算属性。
 
基础例子
<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('')
 
    }
 
  }
 
})
 
计算属性缓存 vs 方法
我们可以通过在表达式中调用方法来达到同样的效果:
 
<p>Reversed message: "{{ reversedMessage() }}"</p>
 
// 在组件中
 
methods: {
 
  reversedMessage: function () {
 
    return this.message.split('').reverse().join('')
 
  }
 
}
 
我们可以将同一函数定义为一个方法而不是一个计算属性。两种方式的最终结果确实是完全相同的。然而,不同的是计算属性是基于它们的响应式依赖进行缓存的。只在相关响应式依赖发生改变时它们才会重新求值。这就意味着只要 message 还没有发生改变,多次访问 reversedMessage计算属性会立即返回之前的计算结果,而不必再次执行函数。
 
计算属性 vs 侦听属性
Vue 提供了一种更通用的方式来观察和响应 Vue 实例上的数据变动:侦听属性。当你有一些数据需要随着其它数据变动而变动时,你很容易滥用 watch——特别是如果你之前使用过 AngularJS。然而,通常更好的做法是使用计算属性而不是命令式的 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: {
 
    // getter
 
    get: function () {
 
      return this.firstName + ' ' + this.lastName
 
    },
 
    // setter
 
    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也会相应地被更新。
 
7.2侦听器
虽然计算属性在大多数情况下更合适,但有时也需要一个自定义的侦听器。这就是为什么 Vue 通过 watch 选项提供了一个更通用的方法,来响应数据的变化。当需要在数据变化时执行异步或开销较大的操作时,这个方式是最有用的。
 
例如:
 
<div id="watch-example">
 
  <p>
 
    Ask a yes/no question:
 
    <input v-model="question">
 
  </p>
 
  <p>{{ answer }}</p>
 
</div>
 
<!-- 因为 AJAX 库和通用工具的生态已经相当丰富,Vue 核心代码没有重复 -->
 
<!-- 提供这些功能以保持精简。这也可以让你自由选择自己更熟悉的工具。 -->
 
 
 
<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>
 
在这个示例中,使用 watch 选项允许我们执行异步操作 (访问一个 API),限制我们执行该操作的频率,并在我们得到最终结果前,设置中间状态。这些都是计算属性无法做到的。
 
除了 watch 选项之外,您还可以使用命令式的 vm.$watch API。
 
 
 
完整代码:
 
7 计算属性和侦听器1
 
<!DOCTYPE html>
 
<html>
 
<head>
    
<title>计算属性和侦听器</title>
    
 
</head>
 
<body>
<div id="example">
  <p>Original message: "{{ message }}"</p>
  <p>Computed reversed message: "{{ reversedMessage }}"</p>
  <p>Computed reversed message: "{{ reversedMessage }}"</p>
</div>
 
<script>
    
var vm = new Vue({
  el: '#example',
  data: {
    message: 'Hello'
  },
  computed: {
    // 计算属性的 getter
    reversedMessage: function () {
  alert("reversedMessage")
      // `this` 指向 vm 实例
      return this.message.split('').reverse().join('')
    }
  }
})
 
</script>
 
</body>
 
</html>
 
 
7 计算属性和侦听器2
 
<!DOCTYPE html>
 
<html>
 
<head>
    
<title>计算属性和侦听器</title>
    
 
</head>
 
<body>
<div id="example">
  <p>Reversed message: "{{ reversedMessage() }}"</p>
  <p>Reversed message: "{{ reversedMessage() }}"</p>
</div>
 
<script>
    
var vm = new Vue({
  el: '#example',
  data: {
    message: 'Hello'
  },
  methods: {
    reversedMessage: function () {
  alert("reversedMessage")
      return this.message.split('').reverse().join('')
    }
  }
})
 
</script>
 
</body>
 
</html>
 
 
7 计算属性和侦听器3
 
<!DOCTYPE html>
 
<html>
 
<head>
    
<title>计算属性和侦听器</title>
    
 
</head>
 
<body>
<div id="demo">{{ fullName }}</div>
 
<script>
    
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
    }
  }
})
 
 
</script>
 
</body>
 
</html>
 
 
7 计算属性和侦听器4
 
<!DOCTYPE html>
 
<html>
 
<head>
    
<title>计算属性和侦听器</title>
    
 
</head>
 
<body>
<div id="demo">{{ fullName }}</div>
 
<script>
    
var vm = new Vue({
  el: '#demo',
  data: {
    firstName: 'Foo',
    lastName: 'Bar'
  },
  computed: {
    fullName: function () {
      return this.firstName + ' ' + this.lastName
    }
  }
})
 
 
</script>
 
</body>
 
</html>
 
 
7 计算属性和侦听器5
 
<!DOCTYPE html>
 
<html>
 
<head>
    
<title>计算属性和侦听器</title>
    
 
</head>
 
<body>
<div id="demo">
  {{ fullName }}<br>
  {{ firstName }}<br>
  {{ lastName }}<br>
</div>
 
<script>
    
var vm = new Vue({
  el: '#demo',
  data: {
    firstName: 'Foo',
    lastName: 'Bar'
  },
  computed: {
    fullName: {
      // getter
      get: function () {
        return this.firstName + ' ' + this.lastName
      },
      // setter
      set: function (newValue) {
        var names = newValue.split(' ')
        this.firstName = names[0]
        this.lastName = names[names.length - 1]
      }
    }
  }// ...
 
})
 
vm.fullName = 'John Doe'
 
</script>
 
</body>
 
</html>
 
 
7 计算属性和侦听器6
 
<!DOCTYPE html>
 
<html>
 
<head>
    
<title>计算属性和侦听器</title>
    
 
</head>
 
<body>
<div id="watch-example">
  <p>
    Ask a yes/no question:
    <input v-model="question">
  </p>
  <p>{{ answer }}</p>
</div>
<!-- 因为 AJAX 库和通用工具的生态已经相当丰富,Vue 核心代码没有重复 -->
<!-- 提供这些功能以保持精简。这也可以让你自由选择自己更熟悉的工具。 -->
<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>
 
</body>
 
</html>

欢迎观看视频教程:https://ke.qq.com/course/432961?tuin=36914f34,如有疑问,请加QQ群665714453交流讨论。
 

猜你喜欢

转载自www.cnblogs.com/daqiang123/p/11368392.html
今日推荐