我试图访问我的根Vue实例中的组件数据。我试图完成的是,你点击一个按钮并出现一组输入。每个输入集都是localStorage中自己的对象,具有密钥id,行李和金额。当我更新一组输入时,它们的值应该在localStorage中更新。我无法弄清楚如何访问我的组件的数据袋和金额。我认为我应该使用的是道具,因为这是我在React中使用的。但是,我不太愿意在Vue中使用它们。VueJS从组件Vue实例中访问数据
这是我到目前为止有:
var STORAGE_KEY = "orders";
var orderStorage = {
fetch: function() {
var orders = JSON.parse(localStorage.getItem(STORAGE_KEY) || "[]");
orders.forEach(function(order, index) {
order.id = index;
});
orderStorage.uid = orders.length;
return orders;
},
save: function(orders) {
localStorage.setItem(STORAGE_KEY, JSON.stringify(orders));
}
};
组件
Vue.component('order', {
template: `
<div>
<select v-model="selected">
<option v-for="option in options" v-bind:value="option.value">
{{ option.text }}
</option>
</select>
<input class="input" id="bags" v-model="bags" type="number" placeholder="Bags">
<input class="input" id="amount" v-model="amount" type="number" placeholder="Amount">
<button @click="$emit('remove')">Remove</button>
</div>
`,
props: {
bags: this.bags, // I must be doing this wrong
amount: this.amount
},
data() {
return {
bags: null,
amount: null,
selected: null,
options: [{
text: "Product (25kg)",
value: 25
}, {
text: "Product (50kg)",
value: 50
}, {
text: "Product (75kg)",
value: 75
}]
}
},
watch: {
bags(newValue) {
this.amount = newValue * this.selected;
},
amount(newValue) {
this.bags = newValue/this.selected;
}
}
});
根Vue的实例
new Vue({
el: '#app',
data: {
orders: orderStorage.fetch(),
bags: null,
amount: null,
},
watch: {
orders: {
handler: function(orders) {
orderStorage.save(orders);
},
deep: true
}
},
methods: {
addProduct: function() {
this.orders.push({
id: orderStorage.uid++,
bags: this.bags, // component.bags ?
amount: this.amount// component.amount?
});
console.log(localStorage);
}
}
});
HTML
<div id="app">
<button @click="addProduct">Add</button>
<div class="orders">
<order v-for="(order, index) in orders" :id="index" :key="order" @remove="orders.splice(index, 1)" :bags="bags" :amount="amount"></order>
</div>
</div>
例如:https://codepen.io/anon/pen/YVwxpz?editors=1010