我試圖訪問我的根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