Vuex 简单而详细的描述

962 阅读3分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

本文同时参与 「掘力星计划」     ,赢取创作大礼包,挑战创作激励金

Hello!掘金的小伙伴们大家好,我是 摸鱼小公举 , #vue组件间的各种传值方法,浏览量不是特别高,而且大家看完之后都不会点赞的;可能掘金大佬多;我技术水平不高,写出的文章可能适合初学者;不管怎样,我还是会更努力的写好每一篇技术文章的;希望大家多多支持,谢谢!今天的文章内容是关于Vuex的相关知识,希望能帮到大家!

src=http___i0.hdslb.com_bfs_article_158854e44d20978f8ed20e1f97cf9eb2a65e0a3c.gif&refer=http___i0.hdslb.gif

正文开始啦~

Vuex的简介

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式;其中有五个属性,state,getters,mutations,actions,modules;

(1) state:vuex的基本数据,用来存储变量

(2) getters:从基本数据(state)派生的数据,相当于state的计算属性

(3) mutations: mutation同步操作,提交更新数据的方法,是通过修改state来直接变更状态

(4) actions:Action异步操作,和mutation的功能大体相同,不同的是Action提交的mutation,而不是直接变更状态;action先会执行异步操作再去调用mutation,随后才跟新state;

(5) modules:模块化vuex,能让每个模块拥有自己的state、mutation、action、getters,使得结构非常清晰,方便管理

Vuex导入vue项目

首先在安装 vuex:

npm install vuex --save

然后在src下创建一个store的文件夹里面新建index.js文件,其文件代码如下 如果项目大有很多数据需要存在vuex里面那么我们可以使用modules模块化;

import Vue from 'vue'
import Vuex from 'vuex'
import user from './modules/user'
import common from './modules/common'
import auth from './modules/auth'
Vue.use(Vuex)
export default new Vuex.Store({
  state: {},
  mutations: {},
  actions: {},
  modules: {
    auth, // 认证
    user, // 用户信息
    common // 公共接口
  }
})

1635131593(1).jpg

模块内容文件里面代码模板

import { getConfig } from '@/api/common'

const state = {
  config: null
}
const getters = {
  config: state => state.config
}
const mutations = {
  SET_CONFIG: (state, data) => {
    state.config = data
  }
}
const actions = {
  // 获取配置信息
  getConfig({ commit }) {
    return new Promise((resolve, reject) => {
      getConfig()
        .then(res => {
          if (res.code == 1) {
            const data = res.data
            commit('SET_CONFIG', data)
          }
          resolve(res)
        })
        .catch(error => {
          reject(error)
        })
    })
  }
}

export default { namespaced: true, state, getters, mutations, actions }

namespaced的描述

vuex中store模块管理,需要store里的index.js中引入各个模块,为了解决不同模块命名冲突问题,需要将不同的模块设置成namespaced:true,然后再不同的页面中引入getters,actions,motations,需要加上所属的模块名称

然后在 main.js 里 引入store

import store from './store'

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

Vuex在vue文件的调用(相关语法)

原生的调用方法

computed:{
//state取值
num1() { return this.$store.state.name }
//getters取值
num2() { return this.$store.getters.filterCount }
}

//mutations 与 actions 更新数据
dispatch:异步操作 ,跟action 一起用  写法: this.$store.dispatch('mutations方法名',值)
commit:同步操作,  跟muction 一起用  写法:this.$store.commit('mutations方法名',值)

vuex的辅助函数加上对象扩展运算符

vuex的辅助函数有mapState , mapGetters , mapMutations , mapActions

首先在vue页面使用要引入相关的辅助函数的方法,用到哪个就引入哪个

//单模块取值

import {mapState,mapGetters, mapMutations, mapActions } from "vuex";

(1) ...mapState 和 ...mapGetters 在computed里面调用 ,取多个值

computed:{
...mapState(['obj','num'])
//取值是
this.obj
this.num

...mapGetters(['getUserId',userName])
//取值是
this.getUserId
this.userName
}

(2) ...mapMutations 和 ...mapActions在methods里面调用
   methods:{
      ...mapMutations(["setGetId"]),
      ...mapActions(['onSetId'])
      
      //更新值直接用this.setGetId("要更新的值")
      //更新值直接用this.onSetId("要更新的值")
   }

//多模块取值

(1) ...mapState 和 ...mapGetters  在computed里面调用 ,

computed:{
...mapState('module',["info"])  //module是模块名称,info是模块里面存储的数据
取值直接就是this.info
//如果要取多个模块的值得再写一个 ...mapState('module',["info"]),

...mapGetters({'infoId':'module/infoId'}) 
这里取多个模块的值可以用对象逗号隔开接着写

不然用数组只能再写一个...mapGetter
...mapGetters('module',["infoId"])
取值直接就是this.infoId

}

(2)...mapMutations 和 ...mapActions  在methods里面调用 ,取多个值

methods:{
...mapMutations('module',[user_name])
...mapActions('user',[user_sex])
}

更新数据:
this.user_name('要更新的值')
this.user_sex('要更新的值')

单纯的js文件里面更新值
this.$store.commit('模块名称/该模块的函数', 更新的值)
this.$store.dispatch('模块名称/该模块的函数', 更新的值)

如果要调用vuex的actions里面的公共方法 一般会将公共api请求接口的方法放在actions里面异步 image.png

  methods:{
  ...mapActions('user', ['getUserInfo']),
  
  然后调用就跟调用普通方法一样 
  (1) this.getUserInfo()
  (2) this.getUserInfo().then(res=>{ 处理数据逻辑})
  }

结语:

XDJMM文章到这来就结束了,相关知识点又复习了一边,所以写文章不仅利他人也利己;写得不好的地方请大家多给些建议;也希望大家多多支持我,谢谢!

「欢迎在评论区讨论,掘金官方将在掘力星计划活动结束后,在评论区抽送100份掘金周边,抽奖详情见活动文章」