Vue Router4的入门

1.main.js

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'


createApp(App)
    .use(router)
    .mount('#app')

2.在src里配置一个router文件夹,里面有index.js,记得提前准备好Hello.vue文件和Nohello.vue文件,我是只在里面放了个按钮

import { createRouter, createWebHashHistory } from 'vue-router'


import nihao from '../views/Hello.vue'
import nibuhao from '../views/Nohello.vue'


const routes = [
  {
    path: "/hello",
    name: "one",
    component: nihao
  },
  {
    path: "/nohello",
    name: "two",
    component: nibuhao
  },

]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})


export default router

3.在App.vue里放入路由出口<router-view/>

<template>
  <img alt="Vue logo" src="./assets/logo.png">
  <HelloWorld msg="Welcome to Your Vue.js App"/>
  <router-view/>
</template>

<script>
import HelloWorld from './components/HelloWorld.vue'

export default {
  name: 'App',
  components: {
    HelloWorld
  }
}
</script>

<style>

</style>

运行后页面先是这样子
在这里插入图片描述
修改网址
在这里插入图片描述
在这里插入图片描述
如果你想点击按钮跳转路由,这样子设置即可

<button @click="navigateToAbout">跳转到Nohello</button>
<script>
export default {
methods: {
  navigateToAbout() {
    this.$router.push('/nohello'); // 使用目标路由的路径进行导航
  }
}
}
</script>

嵌套路由

当你想在一个路由页面里跳转到子路由里面,(app01里面只有一句话)

  {
    path: "/nohello",
    name: "AA",
    component: nibuhao,
    children:[
      {
        path:"one",//此时路由就不用加/了,router会帮你加的
        component:app01
      }
    ]
  }

最关键的一步,一定要在Nohello.vue里加上 <router-view/>

<template>
    <div>
        <button>nohello</button>
        <router-view/>

    </div>
</template>

页面效果
在这里插入图片描述
注意如果是要按钮操作到跳转到子路由,路由一定要写全了
this.$router.push('/nohello'); // 使用目标路由的路径进行导航这样写不对
像这句话一定要写成
this.$router.push('/nohello/one'); // 使用目标路由的路径进行导航

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值