// 使用 Vue Router 进行页面跳转的示例代码
// 1. 首先确保你已经安装并配置了 Vue Router
// 在 main.js 中引入并使用 Vue Router
import Vue from 'vue';
import VueRouter from 'vue-router';
import App from './App.vue';
import Home from './components/Home.vue';
import About from './components/About.vue';
Vue.use(VueRouter);
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About }
];
const router = new VueRouter({
routes
});
new Vue({
router,
render: h => h(App)
}).$mount('#app');
// 2. 在组件中使用 this.$router.push 进行跳转
// 例如在 Home.vue 中添加一个按钮,点击后跳转到关于页面
<template>
<div>
<h1>Home Page</h1>
<button @click="goToAbout">Go to About Page</button>
</div>
</template>
<script>
export default {
methods: {
goToAbout() {
// 使用 push 方法进行导航
this.$router.push({ path: '/about' });
}
}
}
</script>
// 3. 你也可以使用命名路由来进行跳转
// 在路由配置中添加 name 属性
const routes = [
{ path: '/', component: Home, name: 'home' },
{ path: '/about', component: About, name: 'about' }
];
// 然后在组件中使用 name 进行跳转
goToAbout() {
this.$router.push({ name: 'about' });
}
this.$router.push
是 Vue Router 提供的一个方法,用于导航到不同的 URL。你可以通过传递路径或命名路由的方式来进行跳转。/
和 /about
,分别对应 Home
和 About
组件。Home.vue
组件中,我们通过点击按钮调用 goToAbout
方法,使用 this.$router.push
方法导航到 /about
页面。上一篇:vue defineprops
下一篇:vue页面跳转
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站