javascript - vue 計算屬性怎么傳參
問題描述
計算屬性怎么傳參?
<ul> <li v-for='item in goods' : v-text='item.name'></li></ul>data: { goods: [{id: 2,type: 3,name: ’薯片’ },{id: 3,type: 5,name: ’冰紅茶’}]},computed: { goodsType: function(type){switch (type) { case 3:return 'color: #ff9900'break; case 5:return 'color: #00BC0C'break;} }}
問題解答
回答1:傳不了參的,你可以寫成methods
回答2:首先,計算屬性里的方法是傳不了參的,根據你的代碼我想你想要實現的是根據type的改變去返回顏色,那么你應該明白的是計算屬性返回的值只跟它里面的依賴有關,當依賴改變的時候就會觸發計算屬性去重新計算然后改變值,所以你應該讓type變成該vm的一個數據,進而成為該計算屬性的依賴。簡單代碼如下:
data: { goods: [], type: 0 //這個type作為你后面計算屬性的依賴項,通過其他方法改變它的值即可。},computed: { goodsType: function(){//這里將會依賴于此vm的type值,當type值改變,就會重新計算switch (this.type) { case 3:return 'color: #ff9900'break; case 5:return 'color: #00BC0C'break;} }}回答3:
這個需求用一個對象實例數據不就可以解決了嗎?
colors: { 3: ’#ff9900’, 5: ’#00BC0C’}
綁定 style 為 {color: colors[item.type]}
回答4:https://cn.vuejs.org/v2/guide...計算-setter
計算屬性默認只有 getter ,不過在需要時你也可以提供一個 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] } }}// ...
相關文章:
1. python - 獲取到的數據生成新的mysql表2. 為什么python中實例檢查推薦使用isinstance而不是type?3. mysql里的大表用mycat做水平拆分,是不是要先手動分好,再配置mycat4. window下mysql中文亂碼怎么解決??5. sass - gem install compass 使用淘寶 Ruby 安裝失敗,出現 4046. python - (初學者)代碼運行不起來,求指導,謝謝!7. 為啥不用HBuilder?8. python - flask sqlalchemy signals 無法觸發9. python的文件讀寫問題?10. javascript - js 對中文進行MD5加密和python結果不一樣。
