mapState 用法

store代碼:

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
      state.count++
    }
  }
})
export default store

template代碼

<template>
  <div>
     <div>{{count}}</div>
     <div>{{countalias}}</div>
 </div>
</template>
<script>
import { mapState } from 'vuex'
export default {
  name: 'HelloWorld',
  created () {
    // 頁面加載 執行一次
    this.$store.commit('increment')
    console.log(this.$store.state.count)
  },
  computed: {
    // 這種寫法 只是方便調用 個人理解: 不必寫$router.state.count...... 等很長一段代碼  而是直接 this.count 就可以了
    ...mapState({
      count: state => state.count,
      countalias: 'count'
    })
  },
  data () {
    return {
    }
  }
}
</script>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章