[Vue] Vuex 使用
概念性的東西先跳過,這篇主要紀錄使用到的語法。
Store 基本用法:
state: {
// 資料
msg: '',
},
mutations: {
// 接收 action,改變 state,為同步 function
setMsg (state, newValue) {
state.msg = newValue
},
},
actions: {
// 行為,可為非同步
changeMsg ({ commit }) {
setTimeout(function() {
// 呼叫 mutation,使用 store.commit 方法
commit('setMsg', 'hello world');
}, 2000);
}
- 在根目錄引入 (
Vue.use(Vuex)) 之後,子組件可以直接使用this.$store.state取得 state。 - 可以直接在 method 中送出 commit (實務上不建議,建議統一管理)。
methods: {
handleChange: function() {
this.$store.commit('setMsg', this.aboutMsg);
}
}
- 可以使用 mapActions 使用 store 中的 action。
methods: {
...mapActions([
'getHeadlines',
])
}
// map 完可直接使用 this.getHeadlines()