Vue.js Computed Properties of Happy Files

Vue.js computed properties

Computed property keywords: computed.

Computed properties are useful when dealing with some complex logic.

See the following example of reversing a string:

Example 1

<div id="app">
  {
   
   { message.split('').reverse().join('') }}
</div>

The template in Example 1 becomes very complicated, and it is not easy to understand.

Next, let's look at an example of using computed properties:

Example 2

<div id="app">
  <p>原始字符串: {
   
   { message }}</p>
  <p>计算后反转字符串: {
   
   { reversedMessage }}</p>
</div>
 
<script>
var vm = new Vue({
  el: '#app',
  data: {
    message: 'Runoob!'
  },
  computed: {
    // 计算属性的 getter
    reversedMessage: function () {
      // `this` 指向 vm 实例
      return this.message.split('').reverse().join('')
    }
  }
})
</script>

Instance 2 declares a computed property reversedMessage.

The provided function will be used as a getter for the property vm.reversedMessage.

vm.reversedMessage depends on vm.message, and when vm.message changes, vm.reversedMessage will also be updated.


computed vs methods

We can use methods to replace computed, both of which are the same in effect, but computed is based on its dependency cache, and only when the related dependencies change will it re-fetch the value. With methods, the function will always be called again when re-rendering.

Example 3

methods: {
  reversedMessage2: function () {
    return this.message.split('').reverse().join('')
  }
}

Arguably better performance with computed, but if you don't want caching, you can use the methods attribute.


computed setter

Computed properties only have getters by default, but you can also provide a setter if needed:

Example 4

var vm = new Vue({
  el: '#app',
  data: {
    name: 'Google',
    url: 'http://www.google.com'
  },
  computed: {
    site: {
      // getter
      get: function () {
        return this.name + ' ' + this.url
      },
      // setter
      set: function (newValue) {
        var names = newValue.split(' ')
        this.name = names[0]
        this.url = names[names.length - 1]
      }
    }
  }
})
// 调用 setter, vm.name 和 vm.url 也会被对应更新
vm.site = '菜鸟教程 http://www.kxdang.com/topic/';
document.write('name: ' + vm.name);
document.write('<br>');
document.write('url: ' + vm.url);

From the running results of the example, when running vm.site = 'Cainiao Tutorial http://www.kxdang.com/topic/';, the setter will be called, and vm.name and vm.url will be updated accordingly.

Guess you like

Origin blog.csdn.net/weixin_72651014/article/details/130723948