vue3抛弃了vue.use等方法,当使用Vue2的下面的方法时:
import Vue from 'vue' import VueRouter from 'vue-router' Vue.use(VueRouter)会提示错误:
Property 'use' does not exist on type 'typeof import("H:/test/vue3/demo1/node_modules/vue/dist/vue")'.ts(2339)
下面是正确的使用方法:
1、安装vue-router,一定要加上@next,表示是基于vue3的vue-router,否则后面的两个方法createRouter,createWebHashHistory会找不到
npm install vue-router@next --save2、新建组件
components/Home.vue
<template> Home </template> <script lang="ts"> import { defineComponent } from 'vue'; export default defineComponent({ name: 'Home', }); </script>components/News.vue
<template> News </template> <script lang="ts"> import { defineComponent } from 'vue'; export default defineComponent({ name: 'News', }); </script>3、配置路由
新建src/routes.ts配置路由
import {createRouter,createWebHashHistory} from 'vue-router' import Home from "./components/Home.vue" import News from "./components/News.vue" const router = createRouter({ history: createWebHashHistory(), routes: [ { path: '/', component: Home }, { path: '/news', component: News } ], }) export default router;4、挂载路由
在main.ts中挂载路由
import { createApp } from 'vue' import App from './App.vue' import router from './routes' const app = createApp(App) // 挂载路由 app.use(router) app.mount('#app')5、渲染组件
App.vue中通过router-view渲染组件
<template> <router-link to="/">首页</router-link><br> <router-link to="/news">新闻</router-link> <router-view></router-view> </template> <script lang="ts"> import { defineComponent } from 'vue'; export default defineComponent({ name: 'App', }); </script>