vue

vuex的学习和使用

发布于 2024-05-02 17:19:16
浏览量
5577
3 个回答
猫哥
猫哥 项目组成员 2024-05-02
希望我的回答能对你有所帮助

vuex数据状态的设置

image.png
这张图说明的是数据变动流程:

  1. 用户组件触发动作actions(异步操作)
  2. actions 里通过 commit 触发 mutations(同步操作)
  3. mutations 里控制 state 状态的更新
  4. state 变动后组件重新刷新
猫哥
猫哥 项目组成员 2024-05-02
希望我的回答能对你有所帮助

简单总结一下: vuex是vue里用于管理数据状态的工具.

既然是管理数据状态,那主要的关键点就是三个: 状态的设置, 状态的获取, 状态删除.

猫哥
猫哥 项目组成员 2024-05-02
希望我的回答能对你有所帮助

vuex数据状态的获取

最简单的获取状态值

computed:{
    name(){
        return this.$store.state.name  //获取某state中的name值
    }
}
使用computed计算属性是为了当state变动时及时刷新组件

上面的简化方式: (使用mapState)

import {mapState} from "vuex"
computed:{
    ...mapState(['name']),   //属于对上面的简化
}

对mapState内的变量使用别名

    ...mapState({
        new_name: (state)=>state.name,  //使用 new_name代替了name
    })

vuex中的getters定义:

{
    getters:{
        name: state => {
            return state.name
        }
    }
}

之所以定义到vuex里就是因为它时共享的,全局的,所有的组件都可以使用getters里动态state值.

上面的简写使用 mapGetters :

import {mapGetters} from 'vuex'
computed:{
    ...mapGetters(['name'])
}
**vue内使用:this.$store.getters.name**

vuex内的mutations, 相当于vue中的methods,也就是操作状态的方法

mutations:{
    call(state,value){
        state.name = state.name + value
    }
}
**vue调用: this.$store.commit('call','izhangbo')** 对象的方式 this.$store.commit({type:'call',value:'izhangbo'})

对于mutations(定义同步方法)中的方法名,通常使用常量定义来管理

const CALL = 'call';
mutations:{
    [CALL] (state,value){
        state.name = state.name + value
    }
}
**vue调用: this.$store.commit({type:'CALL',value:'izhangbo'})**

对于异步的方法使用actions定义, 它也是类似于methods

actions: {
    callme({commit}, value){
        commit('CALL', value)   //这里就相当于调用mutations内的方法
    }
}
**调用: this.$store.dispatch('callme', {value})**

modules 的作用: 就是将同一模块下的state/getters/mutations/actions/方法常量 都放在一个目录下,定义完之后在 /store/index.js 的全局vuex状态文件内就可以直接使用模块了,(如果没有模块前,所有的状态信息都是定义到这同一个文件内的,项目复杂后会非常庞杂难以管理),模块方式的写法:

import Vue from 'vue'
import Vuex from 'vuex'
import user from './user'
Vue.use(Vuex)

export default new Vuex.Store({
    modules:{
        user,
    }
});
**vue内的调用: this.$store.state.user.name**

学习
记录

发布
问题

分享
好友

手机
浏览

扫码手机浏览