vue3+vite搭建项目(三)

上一章我们讲了怎么看一个新项目以及安装路由

因为我们实际项目中肯定会用到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>


可以正常使用

欢迎留言

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值