前言
幾周前,我寫了關于 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>
新聞熱點
疑難解答
圖片精選