讲了这么久,终于讲到重点了。将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了,看一下解构赋值究竟是怎么回事

Logo

前往低代码交流专区

更多推荐