首頁  >  文章  >  web前端  >  Vue中computed與methods使用區別

Vue中computed與methods使用區別

php中世界最好的语言
php中世界最好的语言原創
2018-05-03 14:09:362150瀏覽

這次帶給大家Vue中computed與methods使用區別,Vue中computed與methods使用的注意事項有哪些,下面就是實戰案例,一起來看一下。

Vue中computed可以用來簡單的拼接需要展示的資料

#computed and methods

拼接展示資料的任務, 也可以用methods完成, 但當頁面的資料變化時, methods中的方法會被重新調用(產生不必要的性能消耗), 而methods內的方法只有和自身有關的數據變化時才會被調用

一個簡單的實例

computed只在初始化時被呼叫

computed只在初始化時被呼叫

methods會在資料變更時被呼叫, 即使變動的資料與自身無關

測試原始碼

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>computed的使用</title>
  <script src="https://cdn.bootcss.com/vue/2.5.16/vue.js"></script>
</head>
<body>
  <p id="root">
  </p>
  <script>
    var vm = new Vue({
      el: "#root",
      data: {
        name: "zhaozhao",
        age: 13,
        hobby: 'Python',
        nameAgeStyle: {
          fontSize: "20px",
          color: "#0c8ac5"
        }
      },
      template: `<p>
        <p v-bind:style="nameAgeStyle">computed方式渲染: {{nameAndAge}}</p>
        <p v-bind:style="nameAgeStyle">methods 方式渲染: {{getNameAndAge()}}</p>
        <br>
        <input type="text" v-model="hobby">
        <p>爱好: {{hobby}}</p>
        <p>{{noUse()}}</p>
        </p>`,
      computed: {
        nameAndAge: {
          get(){
          console.log('调用computed');
          return `${this.name} ==> ${this.age}`;
          }
        }
      },
      methods: {
        getNameAndAge() {
          console.log('调用methods');
          return `${this.name} ==> ${this.age}`;
        },
        noUse(){
          console.log("=methods==nouse==");
        }
      }
    })
  </script>
</body>
</html>

相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!

推薦閱讀:

jQuery Ajax驗證使用者名稱步驟詳解

##v-show新增表達式步驟詳解

以上是Vue中computed與methods使用區別的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn