Vue路由vue-router的简单用法

vueRouter

  • ‌Vue Router‌是Vue.js的官方路由管理器,用于构建单页应用中的页面路由。它提供了丰富的功能,包括路由定义、路由跳转、路由参数传递、嵌套路由等,使得开发者能够方便地管理应用的路由结构。

官网

安装

npm install vue-router

在这里插入图片描述

Demo

在这里插入图片描述

main.js

创建路由

import {createApp} from 'vue'
import './style.css'
import App from './App.vue'
import {createMemoryHistory, createRouter} from "vue-router";
import HelloComp from "./components/HelloComp.vue";
import TestComp from "./components/TestComp.vue";
import HomeComp from "./components/HomeComp.vue";

const router = createRouter({
    history: createWebHistory(),
    routes: [
        {path: '/', component: HomeComp},
        {path: '/hello', component: HelloComp},
        {path: '/test', component: TestComp},
    ]
})

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

  • 或者单独创建一个文件,然后在main中引入
import {createMemoryHistory, createRouter} from "vue-router";
import Home from "../pages/Home.vue";
import About from "../pages/About.vue";
import Error from "../pages/Error.vue";


const routes = [
    {path: '/', component: Home},
    {path: '/about', component: About},
    {path: '/:pathMatch(.*)*', component: Error},
]

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

export default router

App.vue

在<RouterView />中加载路由页面
默认先加载的是{path: '/', component: HomeComp}
<script>


</script>

<template>
  <div>Router测试</div>
  <RouterView />
</template>

<style scoped>

</style>

HomeComp

  • 通过push方法进行跳转
    gotoTest() {
      console.log("goto test")
      this.$router.push('/test')
    },
  • 返回上一级
	gotoBack() {
      this.$router.go(-1)
    },
<script>

export default {

  data() {
    return {
      btn_name_1: "跳转到:测试二维码页面",
      btn_name_2: "跳转到:hello页面",
    }
  },
  methods: {
    gotoTest() {
      console.log("goto test")
      this.$router.push('/test')
    },
    gotoHello() {
      console.log("goto hello")
      this.$router.push('/hello')
    }
  }
}

</script>

<template>

  <h1>测试首页</h1>


  <div style="display: flex;flex-direction: column">
    <button class="btn" v-text="this.btn_name_1" @click="gotoTest()"/>
    <button class="btn" v-text="this.btn_name_2" @click="gotoHello()"/>
  </div>

</template>

<style scoped>

.btn {
  margin: 10px;
}

</style>

其他调用方式

  • 通过useRouter()得到实例,来调用push方法
import {useRouter} from "vue-router";

const router = useRouter()

router.push('/about')

参考文献

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值