天天看點

Vue簡單建立一個項目(九)

url連結裡面最好用的就是傳值了,多會用在頁面跳轉檢視詳情什麼的,也不涉及到安全的情況,是以動态路由傳值就必須要講一下:

比如news頁會有很多主題,他們類似于:

<a href="details.html?id=1" target="_blank" rel="external nofollow" >新聞一</a>
<a href="details.html?id=2" target="_blank" rel="external nofollow" >新聞二</a>
<a href="details.html?id=3" target="_blank" rel="external nofollow" >新聞三</a>
<a href="details.html?id=4" target="_blank" rel="external nofollow" >新聞四</a>
           

點選每一個連結他都會天轉到新的頁面,然而根據不同的傳值,會調取不同的内容展示。

一樣的,隻不過,我們這裡的details.html,會是一個Details.vue元件。

第一種傳值方法:隐?号傳值法

main.js引入元件:

import Details from './components/Details';
           

路由設定

const routes = [
  { path: '/home', component: Home },
  { path: '/news', component: News },
  { path: '/details/:aid', component: Details },//動态路由傳值※※※※※※※※※
  { path: '*', redirect: '/home' }   /*預設跳轉路由*/
]
           

模仿a标簽跳轉并且傳相應的值

<div id="News">
      <h2>我是新聞</h2>
      <ul><li v-for="(item,key) in list"> <router-link :to="'/details/'+key">{{key}}----------{{item}}</router-link></li></ul>
      <button @click="newstohome">給home傳輸局</button>
 </div>
           

然後點選這個連結就跳轉到相應的詳情頁面了,根據傳的值就可以處理頁面了。

第二種傳值方法:顯?号傳值法,又叫做get傳值法

main.js引入元件:

import Details from './components/Details';

const routes = [
  { path: '/home', component: Home },
  { path: '/news', component: News },
  { path: '/details', component: Details },//get傳值※※※※※※※※※
  { path: '*', redirect: '/home' }   /*預設跳轉路由*/
]
           

模仿a标簽跳轉并且傳相應的值

<div id="News">
      <h2>我是新聞</h2>
      <ul><li v-for="(item,key) in list"> <router-link :to="'/details?id='+key">{{key}}----------{{item}}</router-link></li></ul>
      <button @click="newstohome">給home傳輸局</button>
 </div>