Vuex简介

一、什么是vuex

vuex是适用于在Vue项目开发时使用的状态管理工具。

二、vuex的作用

试想一下,如果在一个项目开发中频繁的使用组件传参的方式来同步data中的值,一旦项目变得很庞大,管理和维护这些值将是相当棘手的工作。为此,Vue为这些被多个组件频繁使用的值提供了一个统一管理的工具——VueX。在具有VueX的Vue项目中,我们只需要把这些值定义在VueX中,即可在整个Vue项目的组件中使用。

三、vuex的安装

1、安装指令:

npm install vuex 或者 cnpm install vuex

2、创建vuex目录
在项目的src文件夹内新建一个store文件夹,在该文件夹内再创建index.js
此时你的项目的src文件夹应当是这样的


image.png

3、开始使用vuex
设置store中的index.js

import Vue from 'vue'
import Vuex from 'vuex'
import createPersist from 'vuex-localstorage'
Vue.use(Vuex)
//创建vuex构造器
export default new Vuex.Store({
    state:{
        
    },
    mutations:{

    },
    plugins:[//长久储存
        createPersist(
            {namespace:'namespace-for-state'}
        )
    ],
    modules:{
    }
})

设置main.js

import store from './store/index'//引入vuex
new Vue({
  el: '#app',
  store:store,
  components: { App },
  template: '<App/>'
})

四、vuex的的使用

在组件中使用Vuex

<template>
    <div id='app'>
        name:
        <h1>{{ $store.state.name }}</h1>
    </div>
</template>

或者要在组件方法中使用

methods:{
    add(){
      console.log(this.$store.state.name)
    }
},

VueX中的核心内容
在VueX对象中,其实不止有state,还有用来操作state中数据的方法集,以及当我们需要对state中的数据需要加工的方法集等等成员。
state 是存放状态 和 Vue 实例中的 data遵循相同的规则
使用如下:

import Vue from 'vue'  
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state:{ //声明数据
        str:'',
        obj:{},
        arr:[],
        num:0,
        bool:true/false
    },
})

getters 是加工state成员给外界 ,可以认为是 store 的计算属性。getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。
使用方法如下:

import Vue from 'vue'  
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state:{ //声明数据
        shopCar:[]  
    },
getters:{ //可以认为是 store 的计算属性
        shopCarPrices(state){
            var sum=0
            for(var i=0;i<state.shopCar.length;i++){
                sum+=state.shopCar[i]
            }
            return sum
        }
    }
})

组件中调用

this.$store.getters.shopCarPrices

mutations是对 state成员操作 , Vuex 的 store 中的状态的唯一方法是提交 mutation。
使用方法如下:

import Vue from 'vue'  
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state:{ //声明数据
       name:'helloVueX'   
   },
mutations:{
       amend(state){
state.name = '张三'
       }
   }
})

而在组件中,我们需要这样去调用这个mutation——例如在App.vue的某个method中:

this.$store.commit('amend')

使用Mutation传值

this.$store.commit('amend',15)//传一个值时
this.$store.commit('amend',{age:15,sex:'男'})//传多个值时

接收挂载的参数:

  amend(state,val){
    state.name = '张三'
         console.log(val) // 15或{age:15,sex:'男'}
  }

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

import Vue from 'vue'  
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state:{ 
       key:''
    },
mutations: {
    updateKey(state,val){
        state.key=val
        console.log(state.key);
    }
  },
actions:{
    updateKey(state,val){
        setTimeout(()=>{
            state.commit('updateKey',val)
        },10)
    }
  }
})

在组件中调用:

this.$store.dispatch('updateKey',10)

modules 模块化状态管理,每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割。当项目庞大,状态非常多时,可以采用模块化管理模式。
在创建的store文件夹中在创建一个user.js文件。
在store中的index.js文件中引入刚创建好的user.js文件

import user from './user'

在index文件中写入

 modules:{
        user
    },

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

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

组件中传值

 this.$store.commit('add',res) 
  this.$store.commit('方法名',值) 

组件中调用

this.$store.state.user.username 
user代表的是在这个user模块里 
username 代表的是在user这个模块的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"})
],
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容