上一章我们讲了怎么看一个新项目以及安装路由
因为我们实际项目中肯定会用到vuex进行传值,所以这章我们在vue3+vite项目中来安装搭建vuex
1.首先安装vuex,npm install vuex@next --save
2.在src下面建立store文件夹,在store下面建立index.js文件,modules文件夹,getters.js文件,如图,目录结构这样
//store/index.js
import { createStore } from 'vuex'; //引入vuex
import user from './modules/user'; //引入modules的方法;
import getters from './getters' //引入getters
const store = createStore({
modules: {
user
},
getters
})
export default store;
//store/modules/user.js
// 声明变量
const state = {
age:0,
name:""
};
// 修改变量(state不能直接赋值修改,只能通过mutations)
const mutations = {
add: (state) => {
state.age++;
},
};
// mutations的值由actions传入(异步)
const actions = {
addAsync: ({ commit }) => {
setTimeout(() => {
commit('add');
}, 1000);
},
};
export default {
state,
mutations,
actions
}
//store/getters
const getters = {
age: state => state.user.age //导出age
}
export default getters;
3.在main.js中引入
import { createApp } from 'vue'
import App from './App.vue'
import router from "./router"
import store from './store'
const app=createApp(App)
app.use(router)
app.use(store)
app.mount('#app')
4.在页面中使用
//views/home.vue
<script setup>
import { ref, reactive, computed } from "vue";
import { useStore } from "vuex";
const store = useStore();
//获取age(vue3使用计算属性的方法)
const age = computed(() => store.state.user.age);
function add() {
store.commit("add");
}
</script>
<template>
首页
<h1>{{ age }}</h1>
<button @click="add">age+1</button>
</template>
<style></style>
可以正常使用
欢迎留言