【发布时间】:2018-01-25 13:03:13
【问题描述】:
使用此标记不会触发 Vue JS 计算属性
<!-- language: lang-html -->
<p>£{{plant_price}}</p>
<div v-if="selected.plant.variations.length > 0 ">
<select v-model="selected.plant.selected_variation" class="form-control">
<!-- inline object literal -->
<option v-for="(variation, i) in selected.plant.variations" :selected="variation.id == selected.plant.selected_variation ? 'selected' : ''":value="variation.id">
{{variation.name}}
</option>
</select>
</div>
<!-- language: lang-js -->
var app = new Vue({
el: '#vueApp',
data: {
selected: {
type: {a: '' , b: ''},
vehicle: '',
plant: {
}
},
computed: {
plant_price: function() {
if (this.selected.plant.variations.length > 0 ) {
var variant = _.find(this.selected.plant.variations, {id: this.selected.plant.selected_variation });
return variant.price;
} else {
return this.selected.plant.price;
}
}
...
selected.plant 通过单击植物来填充 - 触发 updateSelected 方法。
<div class="col-sm-4" v-for="(plant, i) in step2.plants">
<div v-on:click="updateSelected(plant)" ....
methods: {
updateSelected: function(plant) {
this.selected.plant = plant; // selected plant
if (this.selected.plant.variations.length > 0 ) {
this.selected.plant.selected_variation = this.selected.plant.variations[0].id; // set the selected ID to the 1st variation
我已经通过调试器进行了检查,可以看到所有正确的属性都可用。
selected:Object
type:Object
vehicle: "Truck"
plant:Object
id:26
price:"52"
regular_price:"100"
selected_variation:421
variations:Array[2]
0:Object
id:420
name:"small"
price:52000
regular_price:52000
1:Object
etc...
我有一个计算属性,它应该根据selected.plant.selected_variation 的值更新plant_price。
我抓住selected.plant.selected_variation 并搜索变体以检索价格。如果不存在变化,则给出植物价格。
我对每个产品都有一个更新所选植物的方法。单击产品会填充 selected.plant 并触发计算的 plant_price 以更新价格(因为 selected.plant.selected_variation 的值已更改)。
但是,计算的 plant_price 不是由选择触发的。选择一个新的变种会做它应该做的,它会更新 selected.plant.selected_variation。然而我的 plant_price 似乎并没有被它触发。
所以我通过取消嵌套 selected.plant.selected_variation 重构了我的代码。我现在把它挂在数据对象上
data = {
selected_variation: ''
}
并更改我的计算机属性以将数据引用为 this.selected_variation。我的计算属性现在可以工作???这对我来说毫无意义?
【问题讨论】:
标签: javascript vue.js vuejs2 vue-component