vuex

vuex概念

5个核心:
state: 存储数据的地方

actions: 异步操作

mutations: 同步操作,只有mutations可以修改state中的数据

getters: 相当于 state的计算属性。

moduleas模块化 modeA, modeB,modeC

用法

vuex对于我来说是在项目状态过多时来帮助管理状态的所以调用的比较多 我总不能一个个繁琐的调用所以这里我就使用了 vuex高级语法糖辅助函数

vuex高级语法糖辅助函数

语法糖 : mapstate,mapActions,mapMutations,mapGetters
可以自定义状态名 数组不可以自定义状态名vuex里是什么他就是什么

数据持久化

我们首先需要npm安装vuex-persistedstate

npm install vuex-persistedstate(普肉谁死特嘚 死得特) --save

然后在vuex里使用import引入
还需要在plugins(铺路跟死)里配置这样才能让我们的state进行数据持久化

详细vuex笔记

vuex概念

五个核心:

state: 存储数据的地方

actions: 异步操作

mutations: 同步操作,只有mutations可以修改state中的数据

getters: 相当于 state的计算属性。

moduleas模块化 modeA, modeB,modeC

初级篇 vuex使用步骤

  1. 安装
    npm install vuex --save

2.创建仓库

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

    //vuex 注册给vue
    Vue.use(Vuex);

    //数据中心
    let state={
        count:10
    }
    //actions 异步操作(定时器,ajax)
    let actions={
       getsync(context,val){
           //context 值得是上下文对象。
         context.commit('increament',val)
       }
    }
    //mutations 同步修改state中的数据
    let mutations={
        increament(state,val){
            //state指的是 state数据中心
           state.count+=val;
        }
    }
    // getters  可以对state中的数据进行计算。(相当于组件中的computed)
    let getters = {
        newVal: (state)=> state.count*2
    }

    //实例化 仓库
    export default new Vuex.Store({
        state,
        actions,
        mutations,
        getters
    });


    //main.js
    import store from './store/index'

    //注入根组件
    new Vue({
        store,
        router,
        components:{xxxx}
    })


    A.vue

     {{this.$store.state.count}}
     {{this.$store.getters.newVal}}
    

     methods:{
         increament(){
             //两种手法
             //1. 通过dispatch()触发actions中的方法修改数据
             this.$store.dispatch('getSync',1)
             //2. 如果同步修改,通过commit()触发mutations中的方法修改。
             this.$store.commit('increament',1)
         }
     }



备注:

1. 只有commit()才可以触发mutations中的方法 (可以在组件中调用,也可以在actions中调用)
2. 只有dispatch()才可以触发actions中的方法 (只能在组件中调用)
3. vuex 是单向数据流
4. 只有mutations才可以修改state中数据。
5. Es6 规范: 
   导入模块  ---> import xxx from '路径'
   导出模块  ---> export default {}
   小小的注意:可以用es6中的解构赋值(按需导入)语法
   import { modea,modeb } from '/home/xxx.js'

   A: 公用的方法库, export default { a:functin(){},b:function(),c:function(){}}

   B:import { c } from '/A.js'

     c()

   commomjs规范(nodejs)
   导入模块:  require('路径')
   导出模块:  module exports { }

vuex高级篇1 、语法糖辅助函数

语法糖,四大金刚辅助函数:mapState,mapActions,mapMutations,mapGetters
当一个组件需要多个状态是,这些状态都声明成计算属性过于冗长。于是有了辅助函数。

import {mapState,mapGetters,mapActions,mapMutations} from 'vuex'


computed:{
    ...mapState({
        a:"a",   //  "a" 指的是state中的a
        b:"b"
    }),
    ...mapGetters({
        Val:'newVal' // 可以重新命名
    })
}

methods:{
    ...mapActions({
        getSync:'getSyncNum'
    })

    ...mapMutations({
        increament:"increament"
    })
}



template

{{a}}  {{b}}

{{getSync(1)}}

<button @click='increament(1)'></button>

高级篇2、 modules 模块化管理数据

状态树结构复杂的时候,可以用modules进行管理。

多人协同开发,可以用modules,避免命名空间冲突。

//创建store,分模块定义

const  test1 ={
    namespaced:true, //开启命名空间,在各组件总 ...mapState("test1",{name:"name"})
    state:{name:'test1'},
    actions:{},
    mutations:{
    changeName(state,arg){
            state.name=arg;
        },
    getters:{}
}

const test2 = {
    namespaced:true,
    state:{},
    actions:{},
    mutations:{
        
        }
    },
    getters:{}
}

new Vuex.Store({
    state:{name:"root"},
    actions,
    mutations,
    getters 
    modules:{
        test1,
        test2
    }

})


在组件中使用:

{{this.$store.state.name}}

{{name}}

{{this.$store.state.test1.name}}

{{tes1Name}}


computed:{
    ...mapState({
        name:“name"
    }),
    ...mapState('test',{   
        test1Name:'name'
    })
}
methods:{
    ...mapMutations('test1',['changeName'])
}



备注:

 ...mapState("test1',['name'])

 ...mapState('test1',{newName:'name'})

 如果展开数组,组件中不可以重命名,
 如果展开时对象,可以重命名

vuex 超级篇 数据持久化

什么是数据持久化?

刷新页面,数据丢失、清空。有时候我们需要把一些数据固话到本地,即使刷新也不能清空,例如:登陆状态、token等。这是就需要用到vuex数据持久化。

安装

npm install vuex-persistedstate --save


在vuex初始化的时候

import createPersistedState from 'vuex-persistedstate'

const state = {
    user:{},
}
export default new Vuex.Store({
    state,
    getters,
    actions,
    mutations,
    plugins:[createPersistedState({
        storage: window.sessionStorage
    })] //会自动保存创建的状态。刷新还在
}
})


createPersistedState()可配置的参数

1.key:storage名称,所有的数据会存储到一个key里面,默认:vuex
s

2.storage:数据存储位置,默认:localStorage。也可以设置sessionStorage。如上。
也可以使用 js-cookie 将状态保存在cookie,如下

首先安装js-cookie

 cnpm install js-cookie --save

  
  import * as Cookies from 'js-cookie'
  import createPersistedState from 'vuex-persistedstate'

  const store = new Vuex.Store({
  // ...
  plugins: [
      createPersistedState({
                storage: {
      getItem: key => Cookies.get(key),
      setItem: (key, value) => Cookies.set(key, value, { expires: 7 }),
      removeItem: key => Cookies.remove(key)
    }

      })
  ]
  })



需要安装 js-cookie
getItem 加载保存的状态
setItem 保存状态
removeItem 删除保存的状态

默认持久化所有state,要想持久化指定state,配置如下:

const store = new Vuex.Store({
  ...
  plugins: [createPersistedState({
      storage: window.sessionStorage,
    reducer(state) {
          return {
            // 只储存state中的list 和test1模块
            list: state.list,
            test1:state.test1
          }
      }
  })]
})

原文地址:https://www.cnblogs.com/luckyjiu9/p/13786293.html