vite2 vue3-ts 添加router, vuex和alias

旧街凉风 提交于 2021-02-08 23:36:34

原文链接: 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";

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!