2016-12-11 20 views
1

私は、値を表示するカウンタと、その値を増やすことができるボタンを持つアプリケーションを持っています。同じコンポーネントの複数のインスタンスが非共有状態であることを確認してください

私はsimple state management from scratch as the docs suggestを使用しました。

「カウンタを追加」ボタンを使用してこのリストにカウンタを追加すると、ページに複数のカウンタが表示されます。親コンポーネント(as per the docs)で別々のキーを持つ私のcounterコンポーネント、counter株式の各インスタンスの各インスタンスにもかかわらず

同じ値:

counters-with-shared-state

どのように私はの個別のインスタンスを追加することができます独自の状態を持つ同じコンポーネントですか?ここで

はwebpackbin上のコードです:http://www.webpackbin.com/41hjaNLXM

コード:

App.vue

<template> 
    <div id="app"> 
    <counter v-for="n in state.countersAmount" :key="n"></counter> 
    <button v-on:click="addCounter">Add a Counter</button> 
    </div> 
</template> 

<script> 
    import Counter from './Counter.vue' 

    const store = { 
    state: { 
     countersAmount: 1 
    }, 
    incrementCounters() { 
     ++this.state.countersAmount 
    } 
    } 

    export default { 
    data() { 
     return { 
     state: store.state 
     } 
    }, 
    methods: { 
     addCounter() { 
     store.incrementCounters() 
     } 
    }, 
    components: { 
     Counter 
    } 
    } 
</script> 

Counter.vue

<template> 
    <div> 
     <h1>{{state.counterValue}}</h1> 
     <button v-on:click="increment">+</button> 
    </div> 
</template> 
<script> 
const store = { 
    state: { 
     counterValue: 0, 
    }, 
    increment() { 
     ++this.state.counterValue 
    } 
} 
export default { 
    data() { 
     return { 
      state: store.state 
     } 
    }, 
    methods: { 
     increment() { 
      store.increment() 
     } 
    } 
} 
</script> 

答えて

2

Counterインスタンスごとに同じstateを使用しています。

const store = { 
    state: { 
    counterValue: 0, 
    }, 
    increment() { 
    ++this.state.counterValue 
    } 
} 

上記のコードは一度だけ実行され、このコンポーネントのすべてのインスタンスは、このstateを共有します。

ちょうどそうと同じように、初期状態として新しいオブジェクトを返す、これを変更するには:あなたが見ることができるよう

<template> 
    <div> 
     <h1>{{counterValue}}</h1> 
     <button v-on:click="increment">+</button> 
    </div> 
</template> 
<script> 

export default { 
    data() { 
     return { 
      counterValue: 0 
     } 
    }, 
    methods: { 
     increment() {    
      ++this.counterValue; 
     } 
    } 
} 
</script> 

シンプルな状態管理スクラッチからリンクされたは、コンポーネント間の共有状態のためであります画像内:

enter image description here

+0

この回答に感謝します。 'data'オブジェクトが不変であると仮定して私は混乱しました。 – alanbuchanan

0

ヨuは常にコンポーネントの同じインスタンスを返します。代わりに、新しいインスタンスを返す必要があります。

関連する問題