Vue路由vue-router的简单用法
vue-router
- 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: createMemoryHistory(),
routes: [
{path: '/', component: HomeComp},
{path: '/hello', component: HelloComp},
{path: '/test', component: TestComp},
]
})
const app = createApp(App)
app.use(router)
app.mount('#app')
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>
参考文献
原文地址:https://blog.csdn.net/yu540135101/article/details/142453828
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!