原文链接: vite2 vue3-ts 添加router, vuex和alias
安装
yarn add vue-router@4
yarn add vuex@next
https://next.vuex.vuejs.org/installation.html
https://github.com/vuejs/vue-router-next
https://next.router.vuejs.org/
https://next.vuex.vuejs.org/installation.html
vuex
store
import { createStore } from "vuex";
const defaultState = {
count: 0,
};
const store = createStore({
state() {
return defaultState;
},
mutations: {
increment(state: typeof defaultState) {
state.count++;
},
},
getters: {
double(state: typeof defaultState) {
return 2 * state.count;
},
},
});
export default store;
app.vue
<template>
<el-button class="flex" @click="add">add</el-button>
{{ count }}--{{ double }}
</template>
<script lang="ts" setup>
import { useStore } from "vuex";
import { defineComponent, reactive, computed } from "vue";
const store = useStore();
const count = computed(() => store.state.count);
const double = computed(() => store.getters.double);
const add = () => {
store.commit("increment");
// store.dispatch("asyncIncrement");
};
</script>
vue-router
import { createRouter, createWebHashHistory } from "vue-router";
import About from "../components/About.vue";
import MainPage from "../pages/MainPage.vue";
const routes = [
{ path: "/", component: MainPage },
{ name: "about", path: "/about", component: About },
];
const router = createRouter({
history: createWebHashHistory(),
routes,
});
export default router;
app.vue
<template>
<el-button class="flex" @click="add">add</el-button>
{{ count }}--{{ double }}
<router-view></router-view>
</template>
<script lang="ts" setup>
import { useStore } from "vuex";
import { defineComponent, reactive, computed } from "vue";
import { useRoute, useRouter } from "vue-router";
const store = useStore();
const count = computed(() => store.state.count);
const router = useRouter();
const route = useRoute();
const double = computed(() => store.getters.double);
const add = () => {
store.commit("increment");
console.log(route, router, route?.query);
router.push({
name: "about",
query: {
...route.query,
},
});
};
</script>
alias
方便使用, 但是会失去跳转...
import { resolve } from "path";
alias: {
"@": resolve(__dirname, "src"),
},
import "@/config/index";
import store from "@/store";
import router from "@/router";
来源:oschina
链接:https://my.oschina.net/ahaoboy/blog/4951184