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>