講了這麼久,終於講到重點了。將vuex用進我們的筆記應用項目
首先建立一個文件夾用來放vuex吧
按照那篇博文的寫法,一個store.js 和 actions.js
再想一下一個筆記應用需要哪些數據呢?
1、筆記數據
2、以及當前活動的筆記數據(即正在編輯的筆記)
好像就只有這個數據了吧。
對於筆記也就只有增刪查改,以及設置當前編輯筆記和喜歡的筆記了
這裏是store.js的代碼,我現在儘量代碼風格都偏向ES2015風格了,以前其實很排斥寫ES6,覺得現在用的JS挺好的啊,但是一種新技術的出現並不是爲了給我們增加工作量,而是爲了使得我們的開發更加便捷。因此刻意去學習使用ES2015,反而會減輕我們的開發工作量呢。
Vue.use(Vuex)
/*定義數據*/
const state = {
notes: [],
activeNote: {}
}
/*定義方法*/
const mutations = {
// 添加筆記
ADD_NOTE: state => {
const newNote = {
text: 'new note',
favorite: false,
header: 'newNote'
}
state.notes.push(newNote),
state.activeNote = newNote
},
//編輯筆記
EDIT_NOTE: (state, text) => {
state.activeNote.text = text;
},
//刪除筆記
DELETE_NOTE: (state) => {
state.notes.$remove(state.activeNote);
state.activeNote = state.notes[0];
},
//標記favorite
TOGGLE_FAVORTE: (state) => {
state.notes.favorite = !state.activeNote.favorite;
},
//設置活動筆記
SET_ACTIVE_NOTE: (state, note) => {
state.activeNote = note;
}
}
const store = new Vuex.Store({
state,
mutations
});
這裏的項目沒有用到getters,寫了actions數據分發;
事件分發這裏我不是特別的懂:
有dispatch,有commit
const actions = {
editNote({
dispatch
}, e) {
dispatch('EDIT_NOTE', e.target.value)
},
}
commit:
actions: {
increment ({ commit }) {
commit('increment')
}
}
這裏的說明是 Action 函數接受一個與 store 實例具有相同方法和屬性的 context 對象,因此你可以調用 context.commit 提交一個 mutation,大概是我對於析構函數了解不清楚吧
文檔說Action 通過 store.dispatch 方法觸發
於是看了一下這篇文章,原來是vue2.x的變化
http://kingsongao.com/blog/2016/07/24/vuex-v2-%E4%B8%AD%E7%9A%84%E4%B8%80%E4%BA%9B%E5%8F%98%E5%8C%96/
所以說如果寫在store裏面,就用commit,寫在外面就用dispatch(僅僅是自己的猜測)
首先就是針對命名的語義化,主要集中在兩個名詞上:commit 與 dispatch。
之前的 store.dispatch 變成了現在的 store.commit,但是 store.dispatch 依然可用,但僅僅用來觸發某些 action。
這裏就懂了actions和getters其實是一樣的道理。
getters可以這樣獲取
computed:{
count(){
return this.$store.state.count
},
notes(){
return this.$store.state.notes
}
},
然後actions也可以這麼寫
methods: {
increment () {
this.$store.commit('increment')
},
decrement () {
this.$store.commit('decrement')
}
}
另一種寫法就是先引入mapActions和mapGetters;
import {mapActions,mapGetters} from 'vuex'
在store裏面,store.js
const actions = {
updateActiveNote: ({
commit
}, payload) => {
commit('SET_ACTIVE_NOTE', payload)
},
addNote: ({
commit
}) => {
commit('ADD_NOTE')
},
deleteNote: ({
commit
}, note) => {
commit('DELETE_NOTE', note)
},
toggleFavorite: ({
commit
}) => {
commit('TOGGLE_FAVORTE')
}
}
因此函數的引入,app.vue
methods:mapActions(['updateActiveNote'])
不過這裏我遇到了一個問題就是我不知道怎麼傳參了。
然後我還是採用的mutation傳參:
this.$store.commit('SET_ACTIVE_NOTE', note)
然後基本上完成了所有的功能了,具體代碼見我的git
https://github.com/daisyHawen/vuex-notes
接着我又要開始學習es6了,看一下解構賦值究竟是怎麼回事