Truyền tham số query qua router-link
Trong Vue Router, bạn có thể truyền dữ liệu giữa các route thông qua tham số query. Có hai cách phổ biến để thực hiện điều này khi sử dụng <router-link>:
- Cách viết dạng chuỗi:
<router-link :to="`/home/message/detail?id=${m.id}&title=${m.title}`">
{{ m.title }}
</router-link>
- Cách viết dạng đối tượng (khuyên dùng):
<router-link :to="{
path: '/home/message/detail',
query: {
id: m.id,
title: m.title
}
}">
{{ m.title }}
</router-link>
Cách viết đối tượng giúp mã rõ ràng hơn và dễ bảo trì, đặc biệt khi tham số tăng lên.
Thu thập tham số query trong component
Để lấy giá trị từ query string, bạn sử dụng $route.query trong template hoặc lifecycle hook:
{{ $route.query.id }}
{{ $route.query.title }}
Hàm mounted() cũng có thể được dùng để in ra toàn bộ đối tượng route nhằm kiểm tra dữ liệu:
mounted() {
console.log(this.$route);
}
Cấu trúc file cơ bản
Banner.vue: Hiển thị tiêu đề ứng dụng.About.vue: Trang giới thiệu đơn giản.Home.vue: Trang chủ với các tab con như News và Message.News.vue,Message.vue: Danh sách nội dung tương ứng.Detail.vue: Hiển thị chi tiết thông điệp dựa trên tham số query.router/index.js: Cấu hình định tuyến chính.
Ví dụ cấu hình router
import VueRouter from 'vue-router';
import About from '../pages/About';
import Home from '../pages/Home';
import News from '../pages/News';
import Message from '../pages/Message';
import Detail from '../pages/Detail';
export default new VueRouter({
routes: [
{
path: '/about',
component: About
},
{
path: '/home',
component: Home,
children: [
{
path: 'news',
component: News
},
{
path: 'message',
component: Message,
children: [
{
path: 'detail',
component: Detail
}
]
}
]
}
]
});
Hiển thị dữ liệu trong Detail.vue
<template>
<ul>
<li>Mã tin nhắn: {{ $route.query.id }}</li>
<li>Tiêu đề: {{ $route.query.title }}</li>
</ul>
</template>
<script>
export default {
name: 'Detail',
mounted() {
console.log('Thông tin route:', this.$route);
}
}
</script>
App.vue - Giao diện chính
<template>
<div>
<div class="row">
<Banner />
</div>
<div class="row">
<div class="col-xs-2 col-xs-offset-2">
<div class="list-group">
<router-link class="list-group-item" active-class="active" to="/about">Giới thiệu</router-link>
<router-link class="list-group-item" active-class="active" to="/home">Trang chủ</router-link>
</div>
</div>
<div class="col-xs-6">
<div class="panel">
<div class="panel-body">
<router-view></router-view>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
import Banner from './components/Banner';
export default {
name: 'App',
components: { Banner }
}
</script>