2021-05-13 Vuex

一、简介

vuex是类似全局对象的形式来管理所有组件的公用数据 如果想修改全局对象的数据 是需要按照vuex提供的方式来修改

二、优点

Vuex状态管理跟使用传统全局变量的不同之处:

1、Vuex的状态存储是响应式的: 就是当你的组件使用到了这个Vuex的状态,一旦它改变了,所有关联的组件会自动更新对应的数据
2、不能直接修改Vuex的状态:如果是个全局对象变量,要修改很容易,但是在Vuex中不能这样做,想修改就得使用Vuex提供的唯一途径:显示的提交(commit) mutations来实现修改 好处就是方便我们跟踪每一个状态的变化,在开发调试的过程中 非常实用

三、步骤

1、安装Vuex
      npm install vuex --save
2、引用vuex
      import Vue from 'vue
      import Vuex from 'vuex
      Vue.use(Vuex)
3、创建仓库Store
     const store =new Vuex.Store({})

在 main.js 文件中,我们将执行以下更新

import Vue from 'vue'
import App from './App'
import store from './store'
new Vue({
  el: '#app',
  store:store,  //store:store 和router一样,将我们创建的Vuex实例挂载到这个vue实例中
  components: { App },
  template: ''
})

主要包括以下几个模块

1、State
    //创建一个store 
    const store =new Vuex.Store({
        state:{
            count:5
        }
    })
    count 就作为全局状态供我们使用
2、Getters

可以认为 getters是store的计算属性,类似于computed,对state里的数据进行一些过滤、改造等待

        getters:{
                 ShopCar(state){                
                }
            },

        在组件中获取{{ShopCar}}方式:
        {{$store.getters.ShopCar}}
3、Mutations
 定义修改数据
      mutations: {    
                updateShopCar(state,val){
                        state.shopCar.push(val)
                      },
      },

       在组件中获取updateShopCar的方式:
        methods: {
              clk(item){
                    this.$store.commit('updateShopCar',item)
              }
        },
4、Actions

actions 是用来专门进行异步操作,最终提交mutation方法。
由于setTimeout是异步操作,所以需要使用actions

export default{
    state:{
        key:''
    },
    mutations: {
        updateKey(state,val){
            state.key=val;
            console.log(val);
        }
    },
    actions:{
        updateKey(state,val){
            setTimeout(()=>{
                //异步处理
                state.commit('updateKey',val)
            },10)
        }
    }
}

        在组件里这么调用就可以
        this.$store.dispatch('updateKey',10)
5、Modules

modules 模块化状态管理,每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割。当项目庞大,状态非常多时,可以采用模块化管理模式。

在创建的store文件夹中在创建一个a.js文件。
在store中的index.js文件中引入刚创建好的a.js文件

import a  from './a'

在index文件中写入

 modules:{
        a:a
    },

创建好的a.js文件中写入模块,可以写入我们需要的核心对象,语法都是一样的
比如:

export default {
    state:{
           username :""
    },
    mutations:{
           add(state,val){
           state.username= val
        },
    },
}

组件中传值

this.$store.commit('add',res) 

组件中调用

this.$store.state.a.username 
a代表的是在这个a模块里 
username代表的是在a这个模块的state中有一个叫username 的变量

plugins是在vue中使用一些插件 列如可以使用vuex-localstorage
vuex-localstorage 要先进行下载 可以使用

npm install vuex-localstorage
cnpm install vuex-localstorage

在index.js中引入 vuex-localstorage

import createPersist from 'vuex-localstorage'

使用方法如下:

plugins:[
        createPersist ({namespace:"namespace-for-state"})
],

你可能感兴趣的:(2021-05-13 Vuex)