vuex笔记

vuex概念

五个核心:

state: 存储数据的地方

actions: 异步操作

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

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

moduleas模块化 modeA, modeB,modeC

初级篇 vuex使用步骤

  1. 安装
    npm install vuex --save
  1. 创建仓库
    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 模块化管理数据

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

  2. 多人协同开发,可以用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数据持久化。

  1. 安装
npm install vuex-persistedstate --save

  1. 在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)
    }

      })
  ]
  })


  1. 需要安装 js-cookie
  2. getItem 加载保存的状态
  3. setItem 保存状态
  4. 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
          }
      }
  })]
})
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

star@星空

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值