如何切换 Vue 路由?创建路由对象,指定路径和组件。将路由对象传递给 Vue 实例。在模板中使用 <router-link> 链接到其他路由。在 JavaScript 中使用 this.$router.push 或 this.$router.replace 在程序中切换路由。

Vue 路由切换
在 Vue.js 应用程序中,可以通过使用路由器来切换路由。
切换路由的步骤:
VueRouter 实例创建一个路由对象,它指定了要显示的组件以及匹配的路径。router 选项将路由对象传递给 Vue 根实例,以便将其与应用程序相关联。<router-link> 组件创建指向其他路由的链接。this.$router.push(path) 或 this.$router.replace(path) 方法在 JavaScript 中编程方式切换路由。详细说明:
立即学习“前端免费学习笔记(深入)”;
创建路由对象:
<code class="js">import Vue from 'vue';
import VueRouter from 'vue-router';
import Home from './components/Home.vue';
import About from './components/About.vue';
Vue.use(VueRouter);
const router = new VueRouter({
routes: [
{
path: '/',
component: Home
},
{
path: '/about',
component: About
}
]
});</code>将路由对象传递给 Vue 实例:
<code class="js">new Vue({
router,
el: '#app'
});</code>在模板中使用路由链接:
<code class="html"><router-link to="/">Home</router-link> <router-link to="/about">About</router-link></code>
在 JavaScript 中编程方式切换路由:
<code class="js">this.$router.push('/about'); // 推送新的路由到历史记录栈
this.$router.replace('/about'); // 替换当前路由历史记录栈中的当前条目</code>以上就是vue路由怎么切换的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号