首页 > 其他 > 详细

vue实例属性之methods和computed

时间:2017-10-13 19:51:01      阅读:321      评论:0      收藏:0      [点我收藏+]

我们可以把同一函数放在methods或者computed中,区别在于computed有缓存,计算属性只有在它的相关依赖发生改变时才会重新求值,即数据改变才会执行函数。而methods每当触发重新渲染时,就会再次执行函数。

一、methods用法

<div id="J_app">
  <p>{{ info }}</p>
  <button v-on:click="reverseText">逆转消息</button>
  <button @click="reverseText">v-on缩写,逆转消息</button>
</div>
var vapp = new Vue({
  el: ‘#J_app‘,
  data: {
    info: ‘Hello Vue.js!‘
  },
  methods: {
    reverseText: function () {
      this.info = this.info.split(‘‘).reverse().join(‘‘)
    }
  }
})

二、computed用法

1、默认用法

<div id="J_app">
  <p>{{ info }}</p>
  <p>{{ reverseText }}</p>
</div>
var vapp = new Vue({
  el: ‘#J_app‘,
  data: {
    info: ‘Hello Vue.js!‘
  },
  computed: {
    reverseText: function () {
      return this.info.split(‘‘).reverse().join(‘‘)
    }
  }
})

2、自定义set
computed默认只有get,可以自定义一个set。

<div id="J_app">
  <p>{{ info }}</p>
  <p>{{ reverseText }}</p>
</div>
var vapp = new Vue({
  el: ‘#J_app‘,
  data: {
    info: ‘Hello Vue.js!‘
  },
  computed: {
    reverseText: {
        get:function () {
          return this.info.split(‘‘).reverse().join(‘‘)
        },
        set:function () {
          this.info = this.info.split(‘‘).reverse().join(‘‘) +‘设置后‘
        }
    }
  }
})
vapp.reverseText ="learn vue from today";

 

vue实例属性之methods和computed

原文:http://www.cnblogs.com/camille666/p/vue_instance_prop_methods_computed.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!