私は、値を表示するカウンタと、その値を増やすことができるボタンを持つアプリケーションを持っています。同じコンポーネントの複数のインスタンスが非共有状態であることを確認してください
私はsimple state management from scratch as the docs suggestを使用しました。
「カウンタを追加」ボタンを使用してこのリストにカウンタを追加すると、ページに複数のカウンタが表示されます。親コンポーネント(as per the docs)で別々のキーを持つ私のcounter
コンポーネント、counter
株式の各インスタンスの各インスタンスにもかかわらず
同じ値:
どのように私はの個別のインスタンスを追加することができます独自の状態を持つ同じコンポーネントですか?ここで
は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>
この回答に感謝します。 'data'オブジェクトが不変であると仮定して私は混乱しました。 – alanbuchanan