[web教学] vue3引入router

[复制链接]
查看558 | 回复0 | 2023-8-23 11:56:06 | 显示全部楼层 |阅读模式 来自 中国北京
1.添加vue-router依靠

        进入项目路径的cmd下,实行命令
        npm install vue-router@4
        大概yarn add vue-router@4
        推荐使用yarn命令,比npm安装更快
2.实行npm install重新加载依靠

3.在src文件夹下创建一个router文件夹

4.在router文件夹下创建index.js文件,内容如下:

        

  1. import { createRouter, createWebHashHistory } from "vue-router"
  2. const routes = [
  3.     {
  4.         path: '/',
  5.         name: 'login',
  6.         component: () => import('@/pages/login')
  7.     },
  8.     {
  9.         path: '/home',
  10.         name: 'home',
  11.         component: () => import('@/pages/home')
  12.     }
  13. ]
  14. export const router = createRouter({
  15.     history: createWebHashHistory(),
  16.     routes: routes
  17. })
  18. export default router
复制代码
        此中 path是访问路径,name时路由名称,component: () => import('@/pages/home')是对应vue组件地点目录。
5.在main.js中引入router文件

  1. import { createApp } from 'vue'
  2. import App from './App.vue'
  3. import router from './router'
  4. const app = createApp(App)
  5. app.use(router)
  6. app.mount('#app')
复制代码
6.设置路由首页

        在App.vue文件中到场路由标签
  1. <template>
  2.   <router-view></router-view>
  3. </template>
  4. <script>
  5. export default {
  6.   name: 'App',
  7.   components: {
  8.   }
  9. }
  10. </script>
  11. <style>
  12. #app {
  13.   font-family: Avenir, Helvetica, Arial, sans-serif;
  14.   -webkit-font-smoothing: antialiased;
  15.   -moz-osx-font-smoothing: grayscale;
  16.   text-align: center;
  17.   color: #2c3e50;
  18.   margin-top: 60px;
  19. }
  20. </style>
复制代码
        此时启动项目后,访问项目根路径就会默认表现路由文件内里设置了路径为“/”的login页面,


7.路由跳转

        假设现在编写两个vue页面,一个是login一个是home,路由设置如上图,那么从login页面跳转到home页面可以使用如下方法:
        在方法中使用this.$router.push('/home')即可跳转至home页面

来源:https://blog.csdn.net/LoveTMW1314/article/details/128420240
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则