vue 点击按钮跳转页面 带参数
时间: 2025-07-24 15:17:16 浏览: 0
在 Vue 中实现点击按钮跳转页面并传递参数,主要依赖于 Vue Router 的 `push` 或 `replace` 方法来完成路由跳转,并通过 `query` 或 `params` 选项传递参数[^1]。
### 实现步骤
#### 1. 定义路由
首先,在 `src/router/index.js` 文件中定义目标页面的路由。例如:
```javascript
{
path: '/target',
component: () => import('@/views/target/Target'),
name: 'Target',
meta: { title: '目标页面' }
}
```
#### 2. 按钮组件绑定点击事件
在需要触发跳转的按钮上绑定一个点击事件,比如 `@click="navigateToTarget"`。
#### 3. 编写跳转逻辑
在 Vue 组件的方法中编写跳转逻辑,使用 `$router.push` 方法进行页面跳转,并携带参数。这里可以使用 `query` 来传递参数,这些参数会在 URL 中以查询字符串的形式出现。
```javascript
methods: {
navigateToTarget() {
// 假设 this.id 是要传递的参数
this.$router.push({
name: 'Target', // 目标页面的名称
query: { id: this.id } // 传递的参数
});
}
}
```
#### 4. 接收参数
在目标页面中,可以通过 `this.$route.query.id` 获取传递过来的参数。通常在组件的生命周期钩子如 `created` 或 `mounted` 中获取参数。
```javascript
created() {
// 获取传递过来的参数
this.receivedId = this.$route.query.id;
}
```
### 示例代码
#### 发送数据的页面
```html
<template>
<div>
<input type="text" v-model="searchQuery" placeholder="输入关键字">
<button @click="navigate">搜索</button>
</div>
</template>
<script>
export default {
data() {
return {
searchQuery: ''
};
},
methods: {
navigate() {
if (this.searchQuery) {
this.$router.push({
name: 'SearchResults',
query: { q: this.searchQuery }
});
}
}
}
};
</script>
```
#### 接收数据的页面
```html
<template>
<div>
<h1>搜索结果</h1>
<p>您搜索的关键字是: {{ receivedQuery }}</p>
</div>
</template>
<script>
export default {
data() {
return {
receivedQuery: ''
};
},
created() {
this.receivedQuery = this.$route.query.q;
}
};
</script>
```
### 注意事项
- 使用 `query` 方式传递参数时,参数会出现在 URL 中,适合传递少量且不敏感的数据。
- 如果需要传递大量或敏感数据,建议使用 `params` 并结合 Vuex 进行状态管理。
- 在 Vue Router 的新版本中,`params` 不再支持直接作为对象传递给 `push`,而是需要使用命名路由和参数名。
###
阅读全文
相关推荐


















