Vue中$route与$router的区别详解
在Vue Router中,$router 和 $route 是两个非常重要的概念,但很多初学者容易混淆它们的作用。本文将通过实例详细讲解两者的区别。
$router 对象
$router 是 VueRouter 的实例对象,包含了路由器的完整配置和导航方法。通过 $router,我们可以进行编程式导航,即通过代码控制页面跳转,而非点击链接。
常用方法包括:
push()- 跳转到指定路由replace()- 替换当前路由back()- 后退forward()- 前进
$route 对象
$route 表示当前激活的路由信息对象。每当路由发生变化时,$route 也会随之更新。该对象包含了当前路由的多种属性:
name- 路由名称path- 路由路径query- URL查询参数params- 动态路由参数
实际应用示例
下面通过一个完整的示例来演示两者的使用场景:
<div id="app">
<nav>
<router-link to="/products">商品列表</router-link>
</nav>
<router-view></router-view>
</div>
// 商品列表组件
const ProductList = {
data() {
return {
products: []
}
},
created() {
// 模拟获取商品数据
this.fetchProducts();
},
methods: {
fetchProducts() {
fetch('/api/products')
.then(response => response.json())
.then(data => {
this.products = data;
});
}
},
template: `
<div class="product-list">
<div v-for="product in products" :key="product.id">
<a @click.prevent="viewDetail(product.id)">
{{ product.name }}
</a>
</div>
</div>
`,
methods: {
viewDetail(id) {
// 使用 $router 进行编程式导航
this.$router.push({
name: 'ProductDetail',
params: { productId: id }
});
}
}
};
// 商品详情组件
const ProductDetail = {
data() {
return {
productId: null,
productInfo: null
}
},
created() {
// 通过 $route 获取路由参数
this.productId = this.$route.params.productId;
this.loadProductDetail();
},
watch: {
// 监听路由变化,重新加载数据
'$route'(to) {
this.productId = to.params.productId;
this.loadProductDetail();
}
},
methods: {
loadProductDetail() {
// 根据商品ID加载详情
console.log('加载商品详情:', this.productId);
},
goBack() {
// 使用 $router 返回上一页
this.$router.back();
},
goToHome() {
// 使用名称导航到首页
this.$router.push({ name: 'Home' });
}
},
template: `
<div>
<h2>商品详情页</h2>
<p>商品ID: {{ productId }}</p>
<button @click="goBack">返回列表</button>
<button @click="goToHome">返回首页</button>
</div>
`
};
const router = new VueRouter({
routes: [
{ path: '/', name: 'Home', component: { template: '<h3>首页内容</h3>' } },
{ path: '/products', name: 'ProductList', component: ProductList },
{ path: '/product/:productId', name: 'ProductDetail', component: ProductDetail }
]
});
new Vue({
el: '#app',
router
});
query参数的使用
除了 params,$route 还可以获取 URL 中的查询参数:
// 假设URL为: /search?keyword=vue&page=1
const SearchResult = {
computed: {
// 通过 $route.query 获取查询参数
keyword() {
return this.$route.query.keyword;
},
page() {
return this.$route.query.page;
}
},
template: `
<div>
<p>搜索关键词: {{ keyword }}</p>
<p>当前页码: {{ page }}</p>
</div>
`,
methods: {
// 跳转到第二页
goToPage(pageNum) {
this.$router.push({
path: '/search',
query: {
keyword: this.keyword,
page: pageNum
}
});
}
}
};
总结
简而言之:
- $router 是路由器实例,用于执行导航操作
- $route 是当前路由信息对象,用于获取路由数据
理解两者的区别后,就能在Vue项目中灵活地进行路由管理和导航控制。