2016-12-14 13 views
1

したがって、複数の子コンポーネントを持つアプリケーションがあります。基本的にスプレッドシート。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]; 
     } 
     } 
    } 
    } 
}); 
+0

これはVuexの完璧な使用例です。 –

答えて

2

I understand props are the way to send data down, but how do I pull data up?

最良の方法は、データアップを引き出すために、カスタムcellコンポーネントにv-modelを使用することです。

参考:https://vuejs.org/v2/guide/components.html#Form-Input-Components-using-Custom-Events

としては、上記のリンクで説明、<input v-model="something">は糖衣構文です:内から

<cell v-model="item" v-for="item in all_cell_items"></cell> 

:だから

<input v-bind:value="something" v-on:input="something = $event.target.value"> 

、あなたの理想的なソリューションは次のようになりますセルコンポーネントの場合は、this.$emit("input", newValue)によって値を親(ルート)コンポーネントに戻すことができます。親コンポーネント(ルート)はクリーンなままで、subTotalの計算されたプロパティを使用できます。

this.cells = [1,2,3,4]のような単純な整数のリストを持ち、v-modelを使用して値をセルコンポーネントに渡そうとすると、これは機能しません。あなたがオブジェクトの配列にあなたのthis.cellsを変更しても大丈夫である場合、あなたが好きそれをやってのクリーンな方法を持っている

[Vue warn]: : You are binding v-model directly to a v-for iteration alias. This will not be able to modify the v-for source array because writing to the alias is like modifying a function local variable. Consider using an array of objects and use v-model on an object property instead.

を::次のエラーになります

<cell v-model="item.price" :label="item.name" v-for="item in all_items"></cell> 

ここで働いてjsFiddleですこの例の場合:https://jsfiddle.net/mani04/9b7n3qmt/

関連する問題