[Vuex系列] - 細說state的幾種用法


state 存放的是一個對象,存放了全部的應用層級的狀態,主要是存放我們日常使用的組件之間傳遞的變量。

我們今天重點講解下state的幾種用法,至於如何從頭開始創建Vuex項目,請看我寫的第一個文章。點擊查看

用法一:使用this.$store

我們還是以一個累加器的例子來看如何實現,具體實現代碼如下:

在state.js文件中添加一個count的變量

const state = {
  count: 0
}
export default state

在src文件夾下新建一個state文件夾,並新建index.vue文件,文件內容如下:

<template>
  <div class="state">
    <h2>{{ count }}</h2>
    <button @click="add">+ADD</button>
  </div>
</template>

<script>
export default {
  computed: {
    count () {
      // 第一種用法
      return this.$store.state.count
    }
  },
  methods: {
    add () {
      // 第一種用法
      this.$store.state.count++
    }
  }
}
</script>

在Vue根實例中注冊了store選項,該store實例會注入到根組件下的所有子組件中,且子組件能通過 this.$store 訪問到。

用法二:引用store.js文件

具體實現代碼如下:

state.js文件內容參考上面的例子,修改state/index.vue,內容如下:

<template>
  <div class="state">
    <h2>{{ count }}</h2>
    <button @click="add">+ADD</button>
  </div>
</template>

<script>
import store from '@/store/store.js'
export default {
  computed: {
    count () {
      // 第二種用法
      return store.state.count
    }
  },
  methods: {
    add () {
      // 第二種用法
      store.state.count++
    }
  }
}
</script>

這種方法在Vue的模塊化的構建系統中,在每個需要使用state的組件中需要頻繁地導入。

用法三:使用mapState輔助函數

具體實現代碼如下:

state.js文件內容參考上面的例子,修改state/index.vue,內容如下:

<template>
  <div class="state">
    <h2>{{ count }}</h2>
  </div>
</template>

<script>
// import store from '@/store/store.js'
import { mapState } from 'vuex'
export default {
  computed: mapState({
    count: state => state.count
  })
}
</script>

<template>
  <div class="state">
    <h2>{{ count }}</h2>
  </div>
</template>

<script>
// import store from '@/store/store.js'
import { mapState } from 'vuex'
export default {
  computed: {
    ...mapState(['count'])
  }
}
</script>

當一個組件需要獲取多個狀態時候,將這些狀態都聲明為計算屬性會有些重復和冗余。為了解決這個問題,我們可以使用 mapState 輔助函數幫助我們生成計算屬性

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM