// 使用 Vue Router 通过 query 方式传参的示例
// router/index.js
import Vue from 'vue';
import Router from 'vue-router';
import Home from '@/components/Home';
import Detail from '@/components/Detail';
Vue.use(Router);
export default new Router({
routes: [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/detail',
name: 'Detail',
component: Detail
}
]
});
// 在 Home.vue 中,使用 <router-link> 或编程式导航来传递参数
<template>
<div>
<h1>Home Page</h1>
<!-- 使用 <router-link> 传递 query 参数 -->
<router-link :to="{ path: 'detail', query: { id: 123, name: 'example' } }">Go to Detail</router-link>
<!-- 或者使用编程式导航 -->
<button @click="goToDetail">Go to Detail with Query Params</button>
</div>
</template>
<script>
export default {
methods: {
goToDetail() {
this.$router.push({ path: 'detail', query: { id: 456, name: 'anotherExample' } });
}
}
}
</script>
// 在 Detail.vue 中,接收并使用 query 参数
<template>
<div>
<h1>Detail Page</h1>
<p>ID: {{ $route.query.id }}</p>
<p>Name: {{ $route.query.name }}</p>
</div>
</template>
<script>
export default {
mounted() {
// 你也可以在生命周期钩子中访问 query 参数
console.log(this.$route.query);
}
}
</script>
query
方式传参时,参数会显示在 URL 的查询字符串中(例如:/detail?id=123&name=example
)。<router-link>
组件或编程式导航 (this.$router.push
) 来传递参数。this.$route.query
来访问传递的参数。下一篇:vue获取当前页面的url
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站