vue3 配置路由

超、凢脫俗 2022-10-06 01:56 380阅读 0赞

使用 vue3 配置路由,步骤如下

1、安装路由

  1. npm install vue-router@4

笔者这里的演示项目名称是 vue3-project

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dzanp6Y2Jx_size_16_color_FFFFFF_t_70

2、新建页面

这里创建 view目录,然后在view目录下创建 A.vue B.vue 两个 vue页面文件

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dzanp6Y2Jx_size_16_color_FFFFFF_t_70 1

A.vue内容

  1. <template>
  2. <div>A</div>
  3. </template>

B.vue内容

  1. <template>
  2. <div>B</div>
  3. </template>

3、创建路由配置文件

新建 router目录,然后在 router目录下新建 index.js和 routes.js文件

index.js 文件内容如下

  1. import {createRouter, createWebHistory} from 'vue-router'
  2. import routes from './routes'
  3. const router = createRouter({
  4. history: createWebHistory(),
  5. routes
  6. })
  7. export default router

routes.js 文件内容如下

  1. const routes = [
  2. {
  3. name: 'a',
  4. path: '/a',
  5. component: () => import('@/view/A')
  6. },
  7. {
  8. name: 'b',
  9. path: '/b',
  10. component: () => import('@/view/B')
  11. },
  12. ];
  13. export default routes

在 main.js中配置路由

  1. import { createApp } from 'vue'
  2. import App from './App.vue'
  3. import router from './router/index'
  4. //注意use要在mount之前
  5. createApp(App).use(router).mount('#app')

4、添加 router-view

笔者这里为了演示在 app.vue文件中添加,读者可根据自己的情况进行添加

  1. <template>
  2. <HelloWorld msg="Welcome to Your Vue.js App"/>
  3. <router-view></router-view>
  4. </template>
  5. <script>
  6. import HelloWorld from './components/HelloWorld.vue'
  7. export default {
  8. name: 'App',
  9. components: {
  10. HelloWorld
  11. }
  12. }
  13. </script>
  14. <style>
  15. #app {
  16. font-family: Avenir, Helvetica, Arial, sans-serif;
  17. -webkit-font-smoothing: antialiased;
  18. -moz-osx-font-smoothing: grayscale;
  19. text-align: center;
  20. color: #2c3e50;
  21. margin-top: 60px;
  22. }
  23. </style>

路由控制在 HelloWorld.vue文件中

使用 this.$router.push()方法进行路由跳转

  1. <template>
  2. <div class="hello">
  3. <h1>{
  4. { msg }}</h1>
  5. <div>
  6. <button @click="show('a')">A页面</button>
  7. <button @click="show('b')">B页面</button>
  8. </div>
  9. </div>
  10. </template>
  11. <script>
  12. export default {
  13. name: 'HelloWorld',
  14. props: {
  15. msg: String
  16. },
  17. methods: {
  18. show(index) {
  19. if(index == 'a') {
  20. this.$router.push('/a')
  21. }
  22. if(index == 'b') {
  23. this.$router.push('/b')
  24. }
  25. }
  26. }
  27. }
  28. </script>

5、运行效果

20210610203513483.gif

至此完

发表评论

表情:
评论列表 (有 0 条评论,380人围观)

还没有评论,来说两句吧...

相关阅读

    相关 VUE3 Router

    > 使用Vue Router可以在不同的组件间切换,根据不同的url地址,路由跳转到不同的组件 > > 提供了俩个路由组件 > > <router-link>:用来定义导航