【问题标题】:Ensure multiple instances of the same component have non-shared state确保同一组件的多个实例具有非共享状态
【发布时间】:2016-12-11 13:12:03
【问题描述】:

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

我用simple state management from scratch as the docs suggest

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

尽管我的 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>

【问题讨论】:

    标签: javascript vue.js state


    【解决方案1】:

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

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

    【讨论】:

    • 感谢您的回答。我很困惑,因为我认为 data 对象是不可变的。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2022-11-12
      • 1970-01-01
      • 1970-01-01
      • 2020-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多