vue.js 計(jì)算屬性

在模板中綁定表達(dá)式是非常便利的,但是它們實(shí)際上只用于簡(jiǎn)單的操作。在模板中放入太多的邏輯會(huì)讓模板過(guò)重且難以維護(hù)。例如:

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

在這種情況下,模板不再簡(jiǎn)單和清晰。在實(shí)現(xiàn)反向顯示 message 之前,你應(yīng)該確認(rèn)它。這個(gè)問(wèn)題在你不止一次反向顯示 message 的時(shí)候變得更加糟糕。

這就是為什么任何復(fù)雜邏輯,你都應(yīng)當(dāng)使用 計(jì)算屬性

# 基礎(chǔ)例子

    <div id="example">
      <p>Original message: "{{ message }}"</p>
      <p>Computed reversed message: "{{ reversedMessage }}"</p>
    </div>
    var vm = new Vue({
      el: '#example',
      data: {
        message: 'Hello'
      },
      computed: {
        // a computed getter
        reversedMessage: function () {
          // `this` 指向vm實(shí)例
          return this.message.split('').reverse().join('')
        }
      }
    })

reversedMessage 依賴于 message,當(dāng) message發(fā)生改變時(shí),reversedMessage也隨之更新。

# 計(jì)算緩存 vs Methods

你可能已經(jīng)注意到我們可以通過(guò)調(diào)用表達(dá)式中的method來(lái)達(dá)到同樣的效果:

    <p>Reversed message: "{{ reverseMessage() }}"</p>


    // in component
    methods: {
      reverseMessage: function () {
        return this.message.split('').reverse().join('')
      }
    }

計(jì)算屬性是基于它的依賴緩存。計(jì)算屬性只有在它的相關(guān)依賴發(fā)生改變時(shí)才會(huì)重新取值。這就意味著只要 message 沒(méi)有發(fā)生改變,多次訪問(wèn) reversedMessage 計(jì)算屬性會(huì)立即返回之前的計(jì)算結(jié)果,而不必再次執(zhí)行函數(shù)。

相比而言,每當(dāng)重新渲染的時(shí)候,method 調(diào)用總會(huì)執(zhí)行函數(shù)。

# 計(jì)算屬性 vs Watched Property

Vue.js 提供了一個(gè)方法 $watch ,它用于觀察 Vue 實(shí)例上的數(shù)據(jù)變動(dòng)。當(dāng)一些數(shù)據(jù)需要根據(jù)其它數(shù)據(jù)變化時(shí), $watch很誘人 —— 特別是如果你來(lái)自 AngularJS 。不過(guò),通常更好的辦法是使用計(jì)算屬性而不是一個(gè)命令式的 $watch回調(diào)。思考下面例子:

<div id="demo">{{ fullName }}</div>
var vm = new Vue({
  el: '#demo',
  data: {
    firstName: 'Foo',
    lastName: 'Bar',
    fullName: 'Foo Bar'
  },
  watch: {
    firstName: function (val) {
      this.fullName = val + ' ' + this.lastName
    },
    lastName: function (val) {
      this.fullName = this.firstName + ' ' + val
    }
  }
})

上面代碼是命令式的和重復(fù)的。跟計(jì)算屬性對(duì)比:

    var vm = new Vue({
      el: '#demo',
      data: {
        firstName: 'Foo',
        lastName: 'Bar'
      },
      computed: {
        fullName: function () {
          return this.firstName + ' ' + this.lastName
        }
      }
    })

# 計(jì)算 setter

計(jì)算屬性默認(rèn)只有 getter ,不過(guò)在需要時(shí)你也可以提供一個(gè) setter :

    // ...
    computed: {
      fullName: {
        // getter
        get: function () {
          return this.firstName + ' ' + this.lastName
        },
        // setter
        set: function (newValue) {
          var names = newValue.split(' ')
          this.firstName = names[0]
          this.lastName = names[names.length - 1]
        }
      }
    }
    // ...

運(yùn)行 vm.fullName = 'John Doe'時(shí), setter 會(huì)被調(diào)用, vm.firstNamevm.lastName 也會(huì)被對(duì)應(yīng)更新。

# 觀察 Watchers

雖然計(jì)算屬性在大多數(shù)情況下更合適,但有時(shí)也需要一個(gè)自定義的 watcher 。這是為什么 Vue 提供一個(gè)更通用的方法通過(guò) watch 選項(xiàng),來(lái)響應(yīng)數(shù)據(jù)的變化。當(dāng)你想要在數(shù)據(jù)變化響應(yīng)時(shí),執(zhí)行異步操作或開銷較大的操作,這是很有用的。

    <div id="watch-example">
      <p>
        Ask a yes/no question:
        <input v-model="question">
      </p>
      <p>{{ answer }}</p>
    </div>

    <!-- Since there is already a rich ecosystem of ajax libraries    -->
    <!-- and collections of general-purpose utility methods, Vue core -->
    <!-- is able to remain small by not reinventing them. This also   -->
    <!-- gives you the freedom to just use what you're familiar with. -->
    <script src="https://unpkg.com/axios@0.12.0/dist/axios.min.js"></script>
    <script src="https://unpkg.com/lodash@4.13.1/lodash.min.js"></script>
    <script>
    var watchExampleVM = new Vue({
      el: '#watch-example',
      data: {
        question: '',
        answer: 'I cannot give you an answer until you ask a question!'
      },
      watch: {
        // 如果 question 發(fā)生改變,這個(gè)函數(shù)就會(huì)運(yùn)行
        question: function (newQuestion) {
          this.answer = 'Waiting for you to stop typing...'
          this.getAnswer()
        }
      },
      methods: {
        // _.debounce 是一個(gè)通過(guò) lodash 限制操作頻率的函數(shù)。
        // 在這個(gè)例子中,我們希望限制訪問(wèn)yesno.wtf/api的頻率
        // ajax請(qǐng)求直到用戶輸入完畢才會(huì)發(fā)出
        // 學(xué)習(xí)更多關(guān)于 _.debounce function (and its cousin
        // _.throttle), 參考: https://lodash.com/docs#debounce
        getAnswer: _.debounce(
          function () {
            var vm = this
            if (this.question.indexOf('?') === -1) {
              vm.answer = 'Questions usually contain a question mark. ;-)'
              return
            }
            vm.answer = 'Thinking...'
            axios.get('https://yesno.wtf/api')
              .then(function (response) {
                vm.answer = _.capitalize(response.data.answer)
              })
              .catch(function (error) {
                vm.answer = 'Error! Could not reach the API. ' + error
              })
          },
          // 這是我們?yōu)橛脩敉V馆斎氲却暮撩霐?shù)
          500
        )
      }
    })
    </script>

在這個(gè)示例中,使用 watch 選項(xiàng)允許我們執(zhí)行異步操作(訪問(wèn)一個(gè) API),限制我們執(zhí)行該操作的頻率,并在我們得到最終結(jié)果前,設(shè)置中間狀態(tài)。這是計(jì)算屬性無(wú)法做到的。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容