溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Vue computed計算屬性的使用方法

發(fā)布時間:2020-09-09 11:47:02 來源:腳本之家 閱讀:292 作者:qq_18837459 欄目:web開發(fā)

computed

computed:相當(dāng)于method,返回function內(nèi)return的值賦值在html的DOM上。但是多個{{}}使用了computed,computed內(nèi)的function也只執(zhí)行一次。僅當(dāng)function內(nèi)涉及到Vue實例綁定的data的值的改變,function才會從新執(zhí)行,并修改DOM上的內(nèi)容。

computed和method的對比

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

這個是vue官網(wǎng)一直拿來作為例子的代碼。在{{}}可以很方便的放入單個表達(dá)式,但是當(dāng)一個HTML的DOM里面存在太多的表達(dá)式,程序會變得很笨重難于維護(hù)。

html

<div id="app9">
  9、method與computed的區(qū)別<br/>
  fullName<br/>
  {{fullName}}<br/>
  fullName2<br/>
  {{fullName}}<br/>
  fullNameMethod<br/>
  {{getFullName()}}<br/>
  fullNameMethod2<br/>
  {{getFullName()}}<br/>
</div>

js

var app9 = new Vue({
  el: '#app9',
  data: {
    firstName: 'Foo',
    lastName: 'Bar'
  },
  methods:{
    getFullName:function () {
      console.log("執(zhí)行了methods")
      return this.firstName+" " +this.lastName;
    }
  },
  computed: {
    fullName: function () {
      console.log("執(zhí)行了computed")
      return this.firstName + ' ' + this.lastName
    }
  }
})
setTimeout('app9.firstName="Foo2"',3000);

控制臺輸出的結(jié)果

執(zhí)行了computed
執(zhí)行了methods
執(zhí)行了methods
執(zhí)行了computed
執(zhí)行了methods
執(zhí)行了methods 

由此可見使用computed,function只會執(zhí)行一次。當(dāng)Vue實例中綁定的data數(shù)據(jù)改變的時候,computed也相對應(yīng)的只改變一次。

相同點(diǎn):在以上代碼中,兩個p標(biāo)簽都會打印出同樣被反轉(zhuǎn)的Hello。

不同點(diǎn):
使用了methods的:HTML中,每一個調(diào)用了Vue的methods的方法,都需要執(zhí)行一遍reversedMessage()這個方法;
而使用computed計算屬性的,只執(zhí)行一遍將結(jié)果保存在緩存中。

computed和watch的對比

html

<div id="demo">{{ fullName }}</div>

js

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
 }
 }
})
var vm = new Vue({
 el: '#demo',
 data: {
 firstName: 'Foo',
 lastName: 'Bar'
 },
 computed: {
 fullName: function () {
  return this.firstName + ' ' + this.lastName
 }
 }
})

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI