前言
几周前,我写了关于 Vue 路由的使用和在 Vue 页面导航的文章。这是在应用程序中探索的一个基本例子。
通常,在将导航构建到应用程序中时,您会发现需要将数据从一个页面传递到另一个页面。(不通顺)例如,您遵循 master-detail 模式,其中您有一个数据列表,通过更深入地挖掘可以获得关于列表中特定项的更多信息。
我们将学习如何使用路由和 URL参数以及查询参数在 Vue 页面之间传递数据。
如果你还没有读过我之前的教程或者不熟悉 vue-router 库,我建议你温习一下。
利用 URL 参数在不同页面中传递数据
假设您有一个 web 应用程序,它显示从某个数据库获得的用户列表。这个列表可能只包含姓名信息,但是数据库中的数据可能包含更多的信息,例如地址、电话等。
在典型的场景中,我们使用主键或其他标识符维护这个用户列表,并用于在请求详细信息时查询数据库时。这样的值可非常合适作为 URL 参数在不同页面传递。
为此,目标页面需要获取到 URL 参数。在前面的教程基础上,我们可以将项目 src/router/index.js 中的文件更改为如下所示
import Vue from 'vue'import Router from 'vue-router'import Page1 from '@/components/page1'import Page2 from '@/components/page2'Vue.use(Router)export default new Router({ routes: [ { path: "/", redirect: { name: "Page1" } }, { path: '/page1', name: 'Page1', component: Page1 }, { path: '/page2/:id', name: 'Page2', component: Page2 } ]})
注意,Page2 的路由中路径中包含一个 :id。这个冒号表示我们正在处理一个变量
打开项目src/components/page1.vue文件,将<template>块改为下面的样子,获取 URL 中的参数
<template> <div class="hello"> <h1>{{ msg }}</h1> <router-link :to="{ name: 'Page2', params: { id: 1234 } }">Navigate to Page2</router-link> </div></template>
在上面的代码片段中,我们选择将参数传递给指定的路由。该 id 将匹配先前在路由定义的参数。您可以定义多个参数,但是要小心,因为它们很容易造成问题
在接收端,我们需要弄清楚如何获取和处理路由参数。
打开 src/components/page2.vue 文件:
<template> <div class="hello"> <h1>{{ msg }}, your id is {{ id }}</h1> <a style="cursor: pointer; text-decoration: underline" v-on:click="navigate()">Navigate to Page1</a> </div></template><script> import router from '../router' export default { name: 'Page2', data () { return { id: 0, msg: 'Hey Nic Raboy' } }, created() { this.id = this.$route.params.id; }, methods: { navigate() { router.go(-1); } } }</script><style scoped> h1, h2 { font-weight: normal; } ul { list-style-type: none; padding: 0; } li { display: inline-block; margin: 0 10px; } a { color: #42b983; }</style>
新闻热点
疑难解答
图片精选