繁体   English   中英

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

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

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

正如文档建议的那样,我从头开始使用简单的状态管理

我可以使用“添加计数器”按钮将计数器添加到此列表中,以便页面上有多个计数器。

尽管我的counter组件的每个实例在父组件中都有一个单独的键(根据文档),但counter的每个实例共享相同的值:

具有共享状态的计数器

如何添加具有自己状态的同一组件的单独实例?

这是 webpackbin 上的代码: http ://www.webpackbin.com/41hjaNLXM

代码:

应用程序.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>

计数器.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>

您为每个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>

您链接的从头开始的简单状态管理用于组件之间的共享状态,如图所示:

在此处输入图像描述

您总是返回相同的组件实例。 相反,您应该返回一个新实例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM