Vuex学习总结

Vuex学习总结

安装:具体思路:

1.导入vuex插件
2.创建vuex的js文件(具体操作在这里完成)
3.在man.js中全局引用
npm install vuex --save
然后 在src文件目录下新建一个名为vuex的文件夹,为方便引入并在vuex文件夹里新建一个store.js,里面的内容如下:
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const store = new Vuex.Store();

export default store;
接下来,在 main.js里面引入store,然后再全局注入一下,这样一来就可以在任何一个组件里面使用this.$store了:
import store from './store'//引入store

new Vue({
  el: '#app',
  router,
  store,//使用store
  template: '<App/>',
  components: { App }
})

-----------------------------------------分割线---------------------------------------------

store.js具体使用方法
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const state={ //要设置的全局访问的state对象
showFooter: true,
 changableNum:0
 //要设置的初始属性值
};

//使用方法:
//  this.$store.state.showFooter或this.$store.state.changebleNum
    在任何一个组件里面获取showfooter和changebleNum定义的值

const getters = { //实时监听state值的变化(最新状态)
isShow(state) {  //承载变化的showFooter的值
   return state.showFooter
},
getChangedNum(){  //承载变化的changebleNum的值
   return state.changableNum
}
}
//使用方法:
 this.$store.getters.getChangedNum
const mutations = { 
  //同步 show(state) {
  //自定义改变state初始值的方法,这里面的参数除了state之外还可以再传额外的参数(变量或对象);
    state.showFooter = true; },
    hide(state)
      { //同上 state.showFooter = false; },
      newNum(state,sum){
      //同上,这里面的参数除了state之外还传了需要增加的值sum state.changableNum+=sum;
    } };
//使用方法:
//  用 this.$store.commit('show') 或 this.$store.commit('hide')
    以及 this.$store.commit('newNum',6) 在别的组件里面进行改变showfooter
    和changebleNum的值
const actions = { 
  //异步 hideFooter(context)
    { //自定义触发mutations里函数的方法,context与store 实例具有相同方法和属性 context.commit('hide'); },
    showFooter(context) { //同上注释 context.commit('show'); },
    getNewNum(context,num){ //同上注释,num为要变化的形参 context.commit('newNum',num) } };

//使用方法:
//  用执行
    this.$store.dispatch('hideFooter')
    或this.$store.dispatch('showFooter')
    以及this.$store.dispatch('getNewNum',6) //6要变化的实参
    这样就可以全局改变改变showfooter或changebleNum的值
//实例化Vuex.Store
const store = new Vuex.Store({
   state,
   getters,
   mutations,
   actions
});
export default store;

 

 
 
posted @ 2019-12-03 11:22  待炒的鱼  阅读(139)  评论(0编辑  收藏  举报