vuex详解


目录

一、Vuex 是什么?

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式 + 库。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。

对于组件间的通信方式而言,vuex也是一个可以进行任意组件通信的方法。

二、什么是“状态管理模式”

1.案例引入

代码如下(示例):

const Counter = {
  // 状态
  data () {
    return {
      count: 0
    }
  },
  // 视图
  template: `
    <div>{{ count }}</div>
  `,
  // 操作
  methods: {
    increment () {
      this.count++
    }
  }
}
 
createApp(Counter).mount('#app')

这个状态自管理应用包含以下几个部分:

状态,驱动应用的数据源;

视图,以声明方式将状态映射到视图;

操作,响应在视图上的用户输入导致的状态变化。

以下是一个表示“单向数据流”理念的简单示意:
在这里插入图片描述

三、具体使用方法

1.安装

代码如下(示例):

npm i  -g vue@3

 注释:@3是版本号,vue2用vuex@3版本,vue3用4版本

2.store文件夹的创建

概念:每一个Vuex应用的核心就是Store(仓库),我们可以说Store是一个容器,Store里面的状态与单纯的全局变量是不一样的,无法直接改变Store中的状态。想要改变状态需通过mutation去修改。

在 src根目录下创建文件夹store,并在其下index.js。需包含actions,mutations,state结构如下:

// 引入vue
import Vue  from 'vue'
 
// 引入vuex
import Vuex from 'vuex'
 
// 应用vue插件
Vue.use(Vuex)
 
// actions响应组件中的动作
const actions = {
}
 
// mutations操作数据state
const mutations = {
}
 
// 准备state存储数据
const state = {
   //状态对象
}
 
// 创建store并导出
const store = new Vuex.Store({
        actions,
        mutations,
        state,
})
 
 
//默认导出store
export default store

2.引入store

在main.js中引入store,全局组件都可以使用vuex。

import store from './store'

new Vue({

  render: h => h(App),

  store,

}).$mount('#app')

四、各个状态的核心概念

1.state

state是状态数据,可以通过this.$store.state来直接获取状态,也可以利用vuex提供的mapState辅助函数将state映射到计算属性(computed)中去。

const state = {
	sum:0,
	realname:'张三',
	age:19
}

使用方式

插值引用:{{$store.state.sum}}

使用计算属性

  computed:{
        // 使用计算属性表达
        title( ){
            return this.$store.state.title;
        },
        singer( ){
            return this.$store.state.singer;
        }
        
    },

使用mapState辅助函数

注意:使用辅助函数的前提是要先引入

// 引入mapState,mapGetters

import {mapState,mapMutations,mapActions,mapGetters} from 'vuex';
computed:{
        // 利用mapState辅助函数的简写形式,代替以上的语句,但本质也是生成计算属性
        ...mapState('options',['title','singer']),
       
    },

2.mutations

更改 Vuex 的 store 中的修改状态的唯一方法是提交 mutation。

Vuex 中的 mutation 非常类似于事件:每个 mutation 都有一个字符串的事件类型 (type)和一个回调函数 (handler)。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数。

// 操作state中的数据
mutations :{
    editTitle(state,value){
        state.title = value;
    },
    editSinger(state,value){
        state.singer = value;
    }
},

使用方式

使用methods方法,使用commit操作state中的数据

   <button @click="editTitle('Lover')">更改歌名</button>
 
   更改歌手名字
    editTitle(str){
        this.$store.commit('editTitle',str);
    },

使用mapMutations辅助函数

 // 利用mapMutation辅助函数的简写形式
    ...mapMutations('options',['editTitle','editSinger']),

3.action

Action 提交的是 mutation,而不是直接变更状态。Action 可以包含任意异步操作。

   // 相应组件中的动作,组件中可以通过通过dispatch发送,
// actions 通过commit发送动作告知mutations
 actions:{
    changeSing(context,value){
        setTimeout(()=>{
            context.commit('editTitle',value);
                },3000)
    },
    changeSinger(context,value){
        setTimeout(()=>{
            context.commit('editSinger',value);
                },3000)
    }
},

使用方式

使用methods方法

 <button @click="changeSing('EndGame')">三秒后更改歌名</button>
 
三秒后更改歌名
    changeSing(str){
        setTimeout(()=>{
            this.$store.dispatch('changeSing',str);
        },3000)
    },
     changeSinger(str){
        setTimeout(()=>{
            this.$store.dispatch('changeSinger',str);
        },3000)
    }

使用mapActions辅助函数

 // 使用mapActions辅助函数简写形式
    ...mapActions(['changeSing','changeSinger'])

4.getters

有时候我们需要从 store 中的 state 中派生出一些状态,例如对列表进行过滤并计数,也就是对状态在加工

// 依赖并加工state中的数据,state中的数据也会相应改变
 getters :{
   otherSong(state){
        return state.title = 'Delicate'
    }
}

使用方式

组件中调用数据:{{$store.getters.bigNum}}

使用mapGetters辅助函数

 // 利用mapGetters辅助函数的简写形似
        ...mapGetters('options',['otherSong'])

六、模块化编码(modules)

Vuex 允许我们将 store 分割成模块(module)。

每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割在模块中使用:namespaced: true, 命名空间,添加之后,当前模块下的标识符可以和其它模块相同,用于解决不同模块的命名冲突问题。

import Vue from 'vue';
 
import Vuex from 'vuex';
 
Vue.use(Vuex);
 
const options ={
    namespaced: true,
 
    // 相应组件中的动作,组件中可以通过通过dispatch发送,
// actions 通过commit发送动作告知mutations
 actions:{
    changeSing(context,value){
        setTimeout(()=>{
            context.commit('editTitle',value);
                },3000)
    },
    changeSinger(context,value){
        setTimeout(()=>{
            context.commit('editSinger',value);
                },3000)
    }
},
// 操作state中的数据
mutations :{
    editTitle(state,value){
        state.title = value;
    },
    editSinger(state,value){
        state.singer = value;
    }
},
// 管理store中的数据
state :{
    title:'Daylight',
    singer:'TaylorSwift'
},
// 依赖并加工state中的数据,state中的数据也会相应改变
 getters :{
   otherSong(state){
        return state.title = 'Delicate'
    }
}
 
}
const store = new Vuex.Store({
   modules:{
   options
   }
})
export default store;

原文链接:https://blog.csdn.net/Bonsoir777/article/details/127332806

  • 17
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值