Vuex使用日志

1、什么是Vuex

  • vuex是一个专门为vue.js应用程序开发的状态管理模式,简单来说就是当多个组件共用一份数据时就会用到vuex。
    每一个Vuex应用包含四大部分,即Vue Components,Actions,Mutations,
    State,其中核心是 store(仓库)。“store”基本上就是一个容器,它包含着你的应用中大部分的状态 (state)。
    Vue Components接收用户行为提交至Actions,然后Actions进一步提交commit(所带参数即为Mutations中的函数),
    Mutations接收commit,修改State里面的数据,然后State将数据变化反馈给Vue Components组件。
    总结来说,数据在State中,数据如何改变由Mutations来决定(比如自增,自减),控制Mutations做改变数据的行为由Actions来决定(必须提交commit)。

2、使用实例

2.1、安装

npm install vuex

2.2、在vue项目src目录下创建store.js

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex)

const state = {
  count: 1
}
const mutations = {
    //count实现自增
  increment(state){
    state.count++
  },
  //count实现自减
  decrement(state){
    state.count--
  }
}

const actions = {
  increment: ({commit}) => {
    commit('increment')  /*actions向mutations提交commit*/
  },
  decrement: ({commit}) => {
    commit('decrement')
  }
}
/*模块导出*/
export default new Vuex.Store({state, mutations, actions}) /*Store必须大写*/

2.3、在components文件夹里创建vuex.vue组件

<template lang="html">
  <div class="vuex">
    vuex {{ $store.state.count }} //调用store中state里的count
    <button name="button" type="button" @click="increment">增加</button>
    <button name="button" type="button" @click="decrement">增加</button>
  </div>
</template>
<script>
  import {mapActions} from 'vuex' //导入mapAction函数
  export default {
    //使用mapActions辅助函数将组件的methods映射为store.dispatch调用(需要先在根节点注入store)
    methods: mapActions([
      'increment',
      'decrement'
    ])
  };
</script>
<style lang="css"></style>

2.4、在入口文件中导入store

import Vue from 'vue'
import App from  './App.vue'
import store from './store'
Vue.config.productionTip = false

new Vue({
  render: h => h(App),
  store
}).$mount('#app')

2.5、在App.vue中导入vuex组件

posted @ 2020-03-26 22:24  海常7号  阅读(462)  评论(0编辑  收藏  举报