Vuex学习使用

Vuex

1.什么是Vuex?

Vuex是实现组件全局状态(数据)管理的一种机制,可以方便的实现组件之间的数据共享

没有Vuex和有Vuex的区别,Vuex可以全局管理所有组件的公共数据,并保持数据的一致性

在这里插入图片描述

2.使用Vuex统一管理数据的好处

  • 能够在Vuex中集中管理共享的数据,易于后期开发和维护
  • 能够高效的实现组件中的数据共享,提高开发效率
  • 存储在Vuex中的数据都是响应式的,能够实时的保持数据与页面的同步

3.什么样的数据适合存储在Vuex中

一般情况下,只有组件之间共享的数据,才有必要保存在Vuex中;对于组件中私有的数据,依旧存储在组件自身的data中即可

4.Vuex的基本使用

  1. 安装Vuex依赖包
npm install vuex --save
  1. 导入vuex包
import Vuex from 'vuex'
vue.use(Vuex)
  1. 创建store对象
const store = new Vuex.Store({
    //state中存放的就是全局共享的数据
    state:{
        count:0
    }
})
  1. 将store对象挂载到vue实例中
new Vue({
    el:'#app',
    render:h=>h(app),
    router,
    //将创建的store对象挂载到Vue实例中,所有的组件就都可以直接从store中获取全局的数据了
    store
})

5.Vuex中的核心概念

5.1 State

State 提供唯一的公共数据源,所有共享的数据都要统一放到store的State中进行存储

组件中访问State中数据的 第一种方式:
this.$store.state.全局数据名称
组件中访问State中数据的第二种方式:
  1. 从Vuex中按需导入mapState 函数
import mapState from 'vuex'
  1. 通过导入的mapState 函数,将当前组件需要的全局数据,映射为当前组件的 computed 计算属性
computed:{
	...mapState(['count'])
    //当作组件中定义的计算属性一样使用 {{count}}
}

5.2 Mutation

Mutation 用于变更Store中的数据,只能是同步的数据操作,不能处理异步的任务

  • 只能通过Mutation变更Store中的数据,不可以直接操作Store中的数据
this.$store.state.count ++;
//以上的方式确实可以使Store中的数据发生改变,但是是不规范的,需要通过Mutation变更Store中的数据
  • 通过Mutation变更Stroe中的数据,虽然繁琐一些,但是可以 集中监控所有数据的变换
定义一个mutation对象

首先在store中定义一个 mutaitons 对象,对象中包含多个方法,通过定义的方法修改Store中的数据 ,

mutations 中定义的方法,默认第一个参数都是state, 如果需要接收外部参数,只需要在定义时加入其他的形参即可

const store = new Vuex.Store({
    //state中存放的就是全局共享的数据
    state:{
        count:0
    },
    mutations:{
        add(state){
            //变更状态
            state.count++;
        },
        addN(state,step){
            //变更状态
            state.count+=step;
        },
        sub(state){
            state.count--;
        },
       	subN(state,step){
            //变更状态
            state.count-=step;
        },
    }
})
触发mutation的第一种方式:
  • 在组件中需要修改数据的位置,通过this.$store.commit('方法名') 来触发mutation
//触发mutation
methods:{
	handlel(){
        //触发mutation的第一种方式,commit的作用就是调用某个函数
        this.$store.commit('add')
    },
    handlel1(){
        //同理定义的时候定义了多个参数,则传参的时候直接传参即可
        this.$store.commit('addN',3)
    }
}
触发mutation 的第二种方式:
  1. 从vuex中按需导入mapMutations 函数
import mapMutations from 'vuex';
  1. 通过导入的mapMutations 函数,将需要的mutations函数,映射到当前组件的methods方法,使用时按照methods定义的方法使用
methods:{
    ...mapMutations(['sub','subN']),
    handlel(){        
        this.sub()
    },
    handlel1(){        
        this.subN(3)
    }
}

5.3 Action

Action 用于处理异步任务,相当于是对Mutation的一种补充,异步的处理先经过Action处理之后,再由Action调用Mutation中的方法去变更Stroe中的全局变量

const store = new Vuex.Store({
    //state中存放的就是全局共享的数据
    state:{
        count:0
    },
    mutations:{
        add(state){
            //变更状态
            state.count++;
        },
        addN(state,step){
            //变更状态
            state.count+=step;
        },
        sub(state){
           state.count-- 
        },
       	subN(state,step){
            //变更状态
            state.count-=step;
        },
    },
    Action:{
        addAsync(context){
            //setTimeout 延时异步
            setTimeout(()=>{
                context.commit('add');
            },1000)
        },
        addNAsync(context,step){
            //setTimeout 延时异步
            setTimeout(()=>{
                context.commit('add',step);
            },1000)
        },
        subAsync(context) {
      		//setTimeout 延时异步
            setTimeout(() => {
                context.commit('sub');
            }, 1000)
    	},
    	subNAsync(context, step) {
            //setTimeout 延时异步
            setTimeout(() => {
                context.commit('subN', step);
            }, 1000)
    	}
    }
})
触发Action 的第一种方式:
  • 在组件中需要修改数据的位置,通过this.$store.dispatch('方法名') 来触发Action
//触发mutation
methods:{
	handlel(){
        //触发Action 的第一种方式,dispatch的作用就是调用某个函数
        this.$store.dispatch('addAsync')
    },
    handlel1(){
        //同理定义的时候定义了多个参数,则传参的时候直接传参即可
        this.$store.dispatch('addNAsync',3)
    }
}
触发Action 的第二种方式:
  1. 从vuex中按需导入mapActions 函数
import mapActions  from 'vuex';
  1. 通过导入的mapAction 函数,将需要的mapAction 函数,映射到当前组件的methods方法,使用时按照methods定义的方法使用(和mutation的方式差不多,只是这里变成了Action中的方法,然后在通过Action间接的调用mutation,然后变更数据)
methods:{
    ...mapAction(['subAsync','subNAsync']),
    handlel(){        
        this.subAsync()
    },
    handlel1(){        
        this.subNAsync(3)
    }
}

6. Getter

Getter 用于对Store中的数据经行加工处理形成新的数据

  • Getter 可以对store中已有的数据加工处理之后形成新的数据,类似Vue的计算属性
  • Store 中的数据发生变化,Getter中的数据也会跟随着变化
const store = new Vuex.Store({
    //state中存放的就是全局共享的数据
    state:{
        count:0
    },
    getter:{
    	showNum:state=>{
    		return '当前最新的数量是['+ state.count +']'
    	}
    }
})
使用getter的第一种方式:
this.$store.getters.名称
使用getter的第二种方式
  1. 从vuex中按需导入mapGetters 函数
import mapGetters from 'vuex'
  1. 通过导入的mapGetters 函数,将当前组件需要的getter中的数据,映射为当前组件的 computed 计算属性
computed:{
	...mapGetters(['showNum']);
    //当作组件中定义的计算属性一样使用 {{showNum}}  
}

方式:

this.$store.getters.名称
使用getter的第二种方式
  1. 从vuex中按需导入mapGetters 函数
import mapGetters from 'vuex'
  1. 通过导入的mapGetters 函数,将当前组件需要的getter中的数据,映射为当前组件的 computed 计算属性
computed:{
	...mapGetters(['showNum']);
    //当作组件中定义的计算属性一样使用 {{showNum}}  
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue3使用Vuex的步骤如下:首先,通过Vue CLI 3搭建Vue项目,并安装Vuex。在Vue项目,引入Vuex并创建一个store实例。使用useStore函数来获取store实例。然后,可以在组件通过导入useStore函数来获取store实例,并使用store.commit来提交mutation,实现对state的修改。在Vuex,可以维护state的构建,并通过组件访问store实现组件间的交互。可以使用ajax请求从云端动态获取数据,并实现当前登录用户的动态发帖和删帖功能。最后,可以根据具体需求实现其他功能,如登录验证方式和注册功能。总之,使用Vue3和Vuex可以更方便地管理和共享组件状态,实现组件间的数据交互。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [Vue3 学习——vue使用vuex(超详细)](https://blog.csdn.net/qq_46201146/article/details/125805058)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [Vue CLI 3搭建vue+vuex最全分析(推荐)](https://download.csdn.net/download/weixin_38729607/12951555)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [Vue3Vuex使用](https://blog.csdn.net/qq_45934504/article/details/123462736)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值