先使用vue cli構建一個自己的vue項目
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const store = new Vuex.Store({ state: { count: 0 }
export default store
現在所有的狀態,也就是變量都放到了test.js中,那我們組件怎么才能獲取到狀態修值呢?這里有兩個步驟需要操作
1, vue 提供了注入機制,就是把我們的store 對象注入到根實例中。vue的根實例就是 new Vue 構造函數,然后在所有的子組件中,this.$store 來指向store 對象。在test.js 中,我們export store, 把store已經暴露出去了,new Vue() 在main.js中,所以直接在main.js 中引入store 並注入即可。
import Vue from 'vue' import App from './App' import router from './router' import store from './store/test' Vue.config.productionTip = false /* eslint-disable no-new */ new Vue({ el: '#app', router, store, template: '<App/>', components: { App } })
2, 在子組件中,用computed 屬性, computed 屬性是根據它的依賴自動更新的。所以只要store中的state 發生變化,它就會自動變化。在display.vue 中作下面的更改, 子組件中 this.$store 就是指向store 對象。我們把 test.js 里面的count 變為8, 頁面中就變為了8。
<template> <div> <h3>Count is {{count}}</h3> </div> </template> <script> export default { computed: { count () { return this.$store.state.count } } } </script>
3, 通過computed屬性可以獲取到狀態值,但是組件中每一個屬性(如:count)都是函數,如果有10個,那么就要寫10個函數,且重復寫10遍return this.$store.state,不是很方便。vue 提供了 mapState 函數,它把state 直接映射到我們的組件中。
當然使用mapState 之前要先引入它。它兩種用法,或接受一個對象,或接受一個數組。還是在display.vue 組件下。
對象用法如下:
<script> import {mapState} from "vuex"; // 引入mapState export default { // 下面這兩種寫法都可以 computed: mapState({ count: state => state.count // 組件內的每一個屬性函數都會獲得一個默認參數state, 然后通過state 直接獲取它的屬性更簡潔 count: 'count' // 'count' 直接映射到state 對象中的count, 它相當於 this.$store.state.count, }) } </script>
數組的方法如下:
<script> import {mapState} from "vuex"; export default { computed: mapState([ // 數組 "count" ]) } </script>
4, 還有最后一個問題,如果我們組件內部也有computed 屬性怎么辦?它又不屬於mapState 中。那就用到了對象分割,把mapState函數生成的對象再分割成一個個的,就像最開始的時候,我們一個一個羅列計算屬性,有10個屬性,我們就寫10個函數。
es6中的... 就是分割用的,但是只能分割數組。在ECMAScript stage-3 階段它可以分割對象,所以這時還要用到babel-stage-3; npm install babel-preset-stage-3 --save-dev, 安裝完全后,一定不要忘記在babelrc 就是babel 的配置文件中,寫入stage-3,
否則一直報錯。在頁面中添加個 p 標簽,顯示我們組件的計算熟悉
babelrc
{ "presets": [ ["env", { "modules": false, "targets": { "browsers": ["> 1%", "last 2 versions", "not ie <= 8"] } }], "stage-3" ], "plugins": ["transform-runtime"], "env": { "test": { "presets": ["env", "stage-3"], "plugins": ["istanbul"] } } }
display.vue 組件更改后
<template> <div> <h3>Count is {{count}}</h3> <p>組件自己的內部計算屬性 {{ localComputed }}</p> </div> </template> <script> import {mapState} from "vuex"; export default { computed: { localComputed () { return this.count + 10; }, ...mapState({ count: "count" }) } } </script>
把test.js 中state.count 改為10, 查看一個效果