vue.js 计算属性未触发

Rob*_*Rob 4 javascript vue.js vue-component vuejs2

使用此标记不会触发 Vue JS 计算属性

\n\n
<!-- language: lang-html -->\n<p>\xc2\xa3{{plant_price}}</p>\n\n    <div v-if="selected.plant.variations.length > 0 ">\n      <select v-model="selected.plant.selected_variation" class="form-control">\n        <!-- inline object literal -->\n        <option v-for="(variation, i) in selected.plant.variations" :selected="variation.id == selected.plant.selected_variation ? \'selected\' : \'\'":value="variation.id">\n          {{variation.name}}\n        </option>\n      </select>\n    </div>\n
Run Code Online (Sandbox Code Playgroud)\n\n
\n\n
<!-- language: lang-js -->\nvar app = new Vue({\n  el: \'#vueApp\',\n  data: {\n    selected: {\n      type: {a: \'\' , b: \'\'},\n      vehicle: \'\',\n      plant: {\n      }\n    },\n  computed: {\nplant_price: function() {\n  if (this.selected.plant.variations.length > 0 ) {\n      var variant = _.find(this.selected.plant.variations, {id: this.selected.plant.selected_variation });\n      return variant.price;\n  } else {\n    return this.selected.plant.price;\n  }\n}\n...\n
Run Code Online (Sandbox Code Playgroud)\n\n

selected.plant通过单击植物来填充 - 触发 updateSelected 方法。

\n\n
<div class="col-sm-4" v-for="(plant, i) in step2.plants">\n          <div v-on:click="updateSelected(plant)" ....\n\n methods: {\n      updateSelected: function(plant) {\n             this.selected.plant = plant; // selected plant\n             if (this.selected.plant.variations.length > 0 ) {\n                 this.selected.plant.selected_variation = this.selected.plant.variations[0].id; // set the selected ID to the 1st variation\n
Run Code Online (Sandbox Code Playgroud)\n\n

我已经通过调试器进行了检查,可以看到所有正确的属性都可用。

\n\n
selected:Object\n    type:Object\n    vehicle: "Truck"\n    plant:Object\n       id:26\n       price:"52"\n       regular_price:"100"\n       selected_variation:421\n       variations:Array[2]\n          0:Object\n              id:420\n              name:"small"\n              price:52000\n              regular_price:52000\n          1:Object\n               etc...\n
Run Code Online (Sandbox Code Playgroud)\n\n

我有一个计算属性,它应该plant_price根据 的值更新selected.plant.selected_variation

\n\n

我抓取selected.plant.selected_variation并搜索各种变体以检索价格。如果不存在变化,则给出工厂价格。

\n\n

我对每种产品都有一个方法来更新所选工厂。单击产品会填充 selected.plant 并触发计算出的 plant_price 来更新价格(因为 selected.plant.selected_variation 的值已更改)。

\n\n

但是,计算出的 plant_price 不是由选择触发的。选择一个新变体会执行其预期的操作,它会更新 selected.plant.selected_variation。然而我的 plant_price 似乎并没有被它触发。

\n\n
\n\n

所以我通过取消嵌套 selected.plant.selected_variation 重构了我的代码。我现在将它挂在数据对象上

\n\n
data = {\n    selected_variation: \'\'\n    }\n
Run Code Online (Sandbox Code Playgroud)\n\n

并更改我的计算机属性以将数据引用为 this.selected_variation。我的计算属性现在可以工作了???这对我来说毫无意义?

\n

小智 6

selected.plant.selected_variation 不是反应性的,VM 不会看到您对其所做的任何更改,因为您是在创建 VM 后设置的。

您可以使用 Vue.set() 使其响应

当你的 AJAX 完成后,调用

Vue.set(selected, 'plant', {Plant Object})
Run Code Online (Sandbox Code Playgroud)