vue.js使用之計算屬性與方法返回的差別

來源:互聯網
上載者:User

標籤:函數定義   響應   join   component   word   roc   highlight   model   script   

<!DOCTYPE html><html><head>    <script src="https://unpkg.com/[email protected]"></script>    <meta charset="utf-8" />    <title></title></head><body>    <div id="app-6">        <p v-once v-if="see">{{ message }}</p>        <p   v-if="see">{{ reversedMessage  }}</p>        <p v-if="see">{{ reversedMessages()  }}</p>        <input  v-model="message">        <ol>            <todo-item                       v-for="item in groceryList"                       v-bind:todo="item"                       v-bind:key="item.id"                       ></todo-item>        </ol>    </div></body></html><script>    var app6;    window.onload = function () {        Vue.component(‘todo-item‘, {            template: ‘<li>{{todo.text}}</li>‘,            props:[‘todo‘]        })        app6 = new Vue({            el: ‘#app-6‘,            data: {                see: true,                groceryList: [                    { id: 0, text: ‘蔬菜‘ },                    { id: 1, text: ‘乳酪‘ },                    { id: 2, text: ‘隨便其他什麼人吃的東西‘ }                ],                message: ‘Hello Vue!‘            },
//計算屬性 computed: { reversedMessage: function () { return this.message.split(‘‘).reverse().join(‘‘) } },
//方法返回 methods: { reversedMessages: function () { return this.message.split(‘‘).reverse().join(‘‘) } } }) }</script>

  注意 由於計算屬性與method 與data中的屬性都是儲存在app6這個對象的一級屬性裡面 所以如果重名 後定義的將會覆蓋前定義的對象

官方文檔解釋兩者的差別

我們可以將同一函數定義為一個 method 而不是一個計算屬性。對於最終的結果,兩種方式確實是相同的。然而,不同的是計算屬性是基於它們的依賴進行緩衝的。計算屬性只有在它的相關依賴發生改變時才會重新求值。這就意味著只要 message 還沒有發生改變,多次訪問 reversedMessage 計算屬性會立即返回之前的計算結果,而不必再次執行函數。

這也同樣意味著下面的計算屬性將不再更新,因為 Date.now() 不是響應式依賴:

computed: {now: function () {return Date.now()}}

相比而言,只要發生重新渲染,method 調用總會執行該函數。

文檔地址 https://cn.vuejs.org/v2/guide/computed.html

vue.js使用之計算屬性與方法返回的差別

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.