延續先前 Vuex 筆記,其實我們要註冊引入vuex,可以不用在main.js引入註冊vuex,但這種方法不推薦。

不推薦的寫法 main.js


import Vue from 'vue';
import App from './App.vue';
//註解 import store from './store';

new Vue({
//註解 store,
el: '#app',
render: h => h(App)
})

改到app.vue的<script>引入


import store from './store’;  //<-----新增這段

export default {
 computed:{
 numberView(){
 return store.state.count; // this.$store改成store
 }
 },
 methods:{
 addCount(){
 store.commit('addCount’) // this.$store改成store
 }
 }
}

這樣寫也可以,但不推薦,為什麼呢?

理由有2 1.因為這樣組件一多,每個組件(.vue)只要有使用vuex,每個(.vue)檔案都要在自己的<script>

import store from './store’;

引入vuex,這樣非常麻煩,但是只要在main.js註冊vuex

也就是原本的寫法

import Vue from 'vue';
import App from './App.vue';
import store from './store';

new Vue({
 store,
 el: '#app',
 render: h => h(App)
})

只要在全域new Vue的實例註冊vuex,每個組件都會被動態注入vuex的this.$store

這樣就方便多了!

2.拉回最原本「Vuex 引入與範例筆記」的cli的範例2, 當我們要讀取vuex值到網頁上,我們用computed計算屬性、 當我們要提取、改變vuex值,會用methods屬性存放的方法去改變, 但是只要全域引入vuex,vuex提供了我們更簡單的方法去處理。

原本app.vue是這樣


<template>
 <div>
 <h1>{{numberView}}</h1>
 <button @click="addCount">+</button>
 </div>
</template>

<script>
 export default {
 computed:{
 numberView(){
 return this.$store.state.count;
 }
 },
 methods:{
 addCount(){
 this.$store.commit('addCount')
 }
 }
 }
</script>

因為有在main.js全域引用Vuex,可以使用Vuex提供的方法

改成這樣


<template>
<div>
 <h1>{{count}}</h1>
 <button @click="addCount">+</button>
</div>
</template>

<script>
 import { mapState, mapMutations } from 'vuex’;

 export default {
 computed: mapState(['count']),
 methods: mapMutations(['addCount'])
 }
</script>

從vuex引入vuex自己的方法mapState、mapMutations來處理 引用方法的改動是把原本computed的numberView函式方法名稱拿掉,改成<h1>直接綁定store的state值count

但這樣寫精簡很多囉!

如果今天有好幾個需要mapState和mapMutations的值,我們會用到ES6+新增的...運算子 把app.vue的<script>改成這樣

import { mapState, mapMutations } from 'vuex’;

export default {
 computed: {
 ...mapState(['count']),
 },
 methods: {
 ...mapMutations(['addCount']),
 }
}

透過...運算子把mapState(['count’])的值灑進computed這個物件屬性、把mapMutations(['addCount’])的值灑進methods這個物件屬性

這樣就可以新增其他的值囉

import { mapState, mapMutations } from 'vuex’;

export default {
 computed: {
 ...mapState(['count']),
 ...mapState([‘其他vuex內自訂的state值']),

 ...mapState([‘其他vuex內自訂的state值']),
 ...mapState([‘其他vuex內自訂的state值']),
 },
 methods: {
 ...mapMutations(['addCount']),
 ...mapMutations([‘其他vuex內自訂的方法']),

 ...mapMutations([‘其他vuex內自訂的方法']),
 ...mapMutations([‘其他vuex內自訂的方法']),
 }
}