vue的計(jì)算屬性

body部分:

<div id="app">
   {{message}}
   <p ref='hello'>你好</p>
</div>

js部分:

var vm=new Vue({
    el:'#app',
    data:{
        message:'hello world'
    },
    uname:'jack',
    age:18
})

//el 獲取Vue綁定的元素 console.log(vm.el)
vm.el.style.color='pink' //data 獲取Vue實(shí)例中的數(shù)據(jù) console.log(vm.data)
//options 獲取Vue實(shí)例中的自定義屬性
console.log(vm.options.uname) console.log(vm.options.age)
//refs 獲取所有帶ref屬性的元素
console.log(vm.refs) console.log(vm.refs.hello)

計(jì)算屬性:
案例:hello Vue變成 Vue===hello 雖然{{}}可以解析數(shù)據(jù),但是{{}}中不能寫復(fù)雜的邏輯屬性,所有復(fù)雜的業(yè)務(wù)邏輯都要使用計(jì)算屬性,使用計(jì)算屬性便于后期維護(hù)

<div id='itany'>
<!--   <p>{{msg.split(' ').reverse().join('===')}}</p>   -->
 <h1>{{msg}}</h1>
 <a href="#">{{revMsg}}</a>
</div>

new Vue({
  el:'#itany',
 data:{
   msg:'hello vue'
 },
 computed:{
   revMsg:function(){
      return this.msg.split(' ').reverse().join('===')
   }
  }
  })    

案例:
效果:點(diǎn)擊加貨總價(jià)會(huì)變化

[圖片上傳失敗...(image-160d5c-1537181644315)]

body部分:

<div id="app">
   <button v-on:click='jh'>加貨</button>
   <h1>總價(jià)為:{{tota}}</h1>
</div>

js部分:

new Vue({
    el:'#app',
    data:{
        pack1:{count:5,price:3},
        pack2:{count:8,price:4}
    },
    computed:{
        tota:function(){
            return this.pack1.count*this.pack1.price+this.pack2.count*this.pack2.price
        }
    },
    methods:{
        jh:function(){
            this.pack1.price++
        }
    }
})

有人說(shuō)為什么price加1而最后結(jié)果加5,因?yàn)閜rice+1后的pack1的結(jié)果變?yōu)?4=20,未+1時(shí)53=15,所以結(jié)果每次都加5

?著作權(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)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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