• 使用vite搭建vue3项目(二) 引入vuerouter


    引入vue-router

    npm install vue-router@next --save

    在src目录下创建router文件夹,在文件夹下创建index.ts

    import {createRouter, RouteRecordRaw, Router, createWebHistory} from 'vue-router'
    
    const routes: Array<RouteRecordRaw> = [
        {
            path: '/',
            name: 'Home',
            component: () => import('@/views/Home.vue'),
            meta: {
                title: '首页'
            }
        }
    ]
    
    const router: Router = createRouter({
        history: createWebHistory(),
        routes
    })
    
    export default router

    创建 views/Home.vue

    <template>
    <HelloWorld :msg="msg"></HelloWorld>
    </template>

    <script lang="ts">
    import HelloWorld from "@/components/HelloWorld.vue"
    import { defineComponent } from "vue"
    export default defineComponent({
    name: "Home",
    components: { HelloWorld },
    setup() {
    return {
    msg: "hello World",
    }
    }
    })
    </script>

    在main.ts中引入router

    import {createApp} from 'vue'
    import router from './router/index'
    import App from './App.vue'
    
    createApp(App).use(router).mount('#app')

    将App.vue中内容替换 

    <template>
    <img alt="Vue logo" src="./assets/logo.png" />
    <router-view />
    </template>

    <script>
    export default {
    name: 'App',
    setup() {

    }
    }
    </script>

    运行报错如下,router找不到路径

    下午11:42:12 [vite] Internal server error: Failed to resolve import "@/views/Home.vue" from "src\router\index.ts". Does the file exist?
      Plugin: vite:import-analysis
      File: D:/workspace/test/element-plus-ts/src/router/index.ts
      4  |      path: "/home",
      5  |      name: "Home",
      6  |      component: () => import("@/views/Home.vue"),

    那么需要修改vite.config.ts配置

    import { defineConfig } from 'vite'
    import vue from '@vitejs/plugin-vue'
    import path from 'path'   // 需安装此模块
    
    // https://vitejs.dev/config/
    export default defineConfig({
      plugins: [vue()],
      resolve: {
        alias: {
          '@': path.resolve(__dirname, 'src')
        }
      }
    })

    安装 path模块

    npm install --save-dev @types/node

    不行,则换cnpm安装

    cnpm install --save-dev @types/node

    配置完成,运行

     npm run dev

     

  • 相关阅读:
    !!!C#——进制转换!
    冒泡排序后用二分查找法查找位置
    简陋的4位验证码程序(范围内取随机数)
    这个年龄计算程序相当不科学,体验还是差差哒
    8.7课堂随笔
    字符串中查询关键字
    !汉企的WiFi网速好快
    重度强迫症患者的九九乘法表
    自选数字和范围的整除算法
    day52
  • 原文地址:https://www.cnblogs.com/zsg88/p/15652750.html
Copyright © 2020-2023  润新知