npm install vue-router@4 --save-dev
router.js
import { createRouter, createWebHistory } from 'vue-router' import Component1 from "./components/Component1" import Component2 from "./components/Component2" /** * 创建路由对象 */ const routes = [ { path: '/Component1', component: Component1 }, { path: '/Component2', component: Component2 }, ]; //创建路由 const router = createRouter({ history: createWebHistory(), routes,//定义的路由 }); export default router;
main.js
import { createApp } from 'vue' import App from './App.vue' import router from './router.js' createApp(App).use(router).mount('#app');
App.vue
<template> <div id="app"> <div> <router-link to="/Component1">组件1</router-link> <router-link to="/Component2">组件2</router-link> </div> <router-view></router-view> </div> </template> <script> export default { name: 'App' } </script> <style> #app{ text-align: center; } a { margin: 10px; } </style>
components/Component1.vue
<template> <div> <h3>我是组件1</h3> <p>{{title}}</p> </div> </template> <script> export default { name: "Component1", data(){ return { title: '组件1title' } } } </script> <style scoped> </style>
components/Component2.vue
<template> <div> <h3>我是组件2</h3> <p>{{title}}</p> </div> </template> <script> export default { name: "Component2", data(){ return { title: '组件2title' } } } </script> <style scoped> </style>
刷新浏览器看效果