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>