【发布时间】:2017-09-15 23:33:21
【问题描述】:
我正在尝试访问我的根 Vue 实例中的组件数据。我想要完成的是,您单击一个按钮并出现一组输入。每组输入都是 localStorage 中自己的对象,具有键 id、bags 和 amount。当我更新一组输入时,它们的值应该在 localStorage 中更新。我无法弄清楚如何访问我的组件的袋子和数量数据。我认为我应该使用的是道具,因为那是我在 React 中使用的。但是,我还不太习惯在 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>
【问题讨论】:
标签: javascript vue.js local-storage