zoukankan      html  css  js  c++  java
  • vue实例属性之methods和computed

    我们可以把同一函数放在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";
  • 相关阅读:
    Linux的chattr与lsattr命令详解
    Ant_的最完整build.xml解释
    ant安装和验证
    MySQL ALTER TABLE: ALTER vs CHANGE vs MODIFY COLUMN
    python简单爬虫技术
    selenium自动化测试打开新标签窗口
    js中的相等与不等运算
    table-layout:fixed 属性的解说
    DWZ与KindEditor编辑器的整合
    DWZ框架学习
  • 原文地址:https://www.cnblogs.com/camille666/p/vue_instance_prop_methods_computed.html
Copyright © 2011-2022 走看看