概述
- 引入依赖
- 配置公有vuex
- 配置vuex的配置
- 页面引入使用
引入依赖
npm
npm install vuex@next --save
配置公有vuex
vue
import './assets/main.css'
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './axios/store'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
const app = createApp(App)
app.use(router)
app.use(store)
app.use(ElementPlus)
app.mount('#app')
配置vuex的配置
js
import { createStore } from 'vuex'
const store = createStore({
state: {
token: '',
user: {}
},
mutations: {
token(state, token) {
state.token = token;
},
user(state, user) {
state.user = user;
}
},
getters: {
getToken(state) {
return state.user.token;
},
getUser(state) {
return state.user;
}
}
})
export default store;
页面应用
vue
<template>
<div>
{{ 1 + $store.state.token }} <!-- 使用计算属性 token -->
</div>
<Text></Text>
</template>
<script setup>
import Text from './views/test.vue';
import { onMounted, computed } from 'vue';
import { useStore } from 'vuex'
// 在组件挂载时提交 token
onMounted(() => {
store.commit('token', "fdsfdssfdsfdsfd");
console.log(store.state.token);
});
</script>
<style scoped></style>
<template lang="">
<div>
{{2+ temp}}
</div>
</template>
<script setup>
import { onMounted, computed, ref } from 'vue';
import { useStore } from 'vuex'
const store = useStore();
const temp = ref(0);
// 在组件挂载时提交 token
onMounted(() => {
store.commit('token', "f尽快六角恐龙都结束了飞机到是覅sfd");
console.log(store.state.token);
temp.value = store.state.token;
});
</script>
<style lang="">
</style>
结果:
1f尽快六角恐龙都结束了飞机到是覅sfd
2f尽快六角恐龙都结束了飞机到是覅sfd