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