したがって、複数の子コンポーネントを持つアプリケーションがあります。基本的にスプレッドシート。Vue.jsアプリ内で子コンポーネントを取得する方法
セルが変更されたときにコンポーネントの合計を計算できるようにします。私は、変更イベントが伝播されたときにそれらをキャッシュすることによって、セルのすべての値を格納する方法を見つけました。しかし、これは最善の方法ですか?動的に子供をつかむための良い方法はありますか?私はprops
がデータを送信する方法だと理解していますが、どのようにデータを引き上げるのですか?
これはHTMLです:
<html>
<head>
</head>
<body>
<span id="calculator">
<template v-for="i in 5">
<cell v-bind:index="i" v-on:total="total"></cell>
</template>
{{ subtotal }}
{{ cells }}
</span>
<script src="vue.js"></script>
<script src="app.js"></script>
</body>
</html>
そしてapp.js:
Vue.component('cell', {
template: "<input v-model='value' v-on:change='total' size='10' type='text'/>",
props: {
index: Number
},
data: function() {
return {
value: 0
};
},
methods: {
total: function() {
console.log("Value is now: " + this.value + " for index: " + this.index)
this.$emit('total', this.value, this.index)
}
}
});
var app = new Vue({
data: {
subtotal: 0,
cells: []
},
el: "#calculator",
methods: {
total: function(value, indexPlusOne) {
var index = indexPlusOne-1;
var v = parseInt(value);
Vue.set(this.cells, index, v);
console.log("Inside the total function: " + v + " " + index);
this.subtotal = 0;
for(var i = 0; i < this.cells.length; i++) {
if(this.cells[i]) {
this.subtotal += this.cells[i];
}
}
}
}
});
これはVuexの完璧な使用例です。 –