确保同一组件的多个实例具有非共享状态

Ensure multiple instances of the same component have non-shared state

我有一个应用程序,其中有一个显示值的计数器和一个可以递增该值的按钮。

我用了simple state management from scratch as the docs suggest.

我可以使用 'Add Counter' 按钮将计数器添加到此列表,这样我在页面上就有多个计数器。

尽管我的 counter 组件的每个实例在父组件 (as per the docs) 中都有一个单独的键,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>

您总是return使用组件的同一个实例。相反,您应该 return 一个新实例。

您为每个 Counter 个实例使用相同的 state

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

上面的代码只会执行一次,这个组件的每个实例都会共享这个state

要更改此设置,只需 return 一个新对象作为初始状态,如下所示:

<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>

您链接的 Simple State Management from Scratch 用于组件之间的共享状态,如图所示: