前端——Vuex状态管理

1.store配置

1.1vue3中-index.js

import {
  createStore
} from 'vuex'
//引入Vuex模块
import HomeModule from './modules/HomeModule'
export default createStore({
  state: {},
  getters: {},
  mutations: {},
  actions: {},
  modules: { //引入的Vuex模块在此注册,然后外部就可以通过$store.state.HomeModule.获取数据了
    HomeModule
  }
})

1.2vue3中-模块js

let HomeModule = {
    //state等同于vue2中的data,或者ref reactive创建的响应式数据;
    //Vuex中数据从外部获取,与vue2中类似,通过$store.state获取
    state: {
        navBool: false
    },
    mutations: {
        SET_NAV_BOOL(state) {
            state.navBool = !state.navBool
        }
    },
    actions: {},
    getters: {}
}

export default HomeModule

2.组件中使用store

2.1Vue3中Vuex的使用

获取公用数据与vue2类似,通过$store.state.navBool获取公用数据

2.2Vue3中,Vuex的使用

修改数据,不能像Vue2中通过this.$store获取$store;

Vue3中修改数据需要:

1.引入:import {useStore} from 'vuex';

2. let store=useStore();

3.这样获取到strore后,通过store.commit等方法来修改

<template>
    <div>
        <el-icon @click="ck">
            <!--Vue3中,Vuex的使用:获取公用数据与vue2类似,通过$store.state.navBool获取公用数据 -->
            <ArrowLeftBold v-if="$store.state.HomeModule.navBool" />
            <ArrowRightBold v-else />
        </el-icon>
    </div>
</template>
<script setup>
/* 引入element-plus中的图标 */
//1.按需引入图标
import { ArrowLeftBold, ArrowRightBold } from '@element-plus/icons-vue'
//2.注册引入所有图标
//import * as ElementPlusIconsVue from '@element-plus/icons-vue'
//3.或在main.js中全局引入后use

/*Vue3中,Vuex的使用 */
//修改数据,不能像Vue2中通过this.$store获取$store;
//Vue3中修改数据需要1.引入:import {useStore} from 'vuex';2. let store=useStore();这样获取到strore后,通过store.commit等方法来修改
import { useStore } from 'vuex';
let store = useStore();
let ck = () => {
    console.log("被点击了");
    store.commit('SET_NAV_BOOL')
}



</script>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值