最近在做一個公眾號的商城項目,主要用的VUE+MUI,其實今天這個點對於有過項目經驗的前端工作者來說是最基礎的,但也是必須要掌握的,今天小編主要是記錄下傳參和跳轉的一些總結(僅供參考)。
首先我們先上代碼吧!
<router-link :to="{path:'/editaddress',query:{ id:item.id }}"> <div class="top_left_center"> <img src="/static/images/details/location.png" alt="" class="location_img"> <span style="color:#f40;font-size:15px;">點擊編輯</span> </div> </router-link>
這個是我常用的傳參及跳轉路由的方法,下面剪短說一下這個代碼,在router-link中:to后面跟着的就是主角(跳轉、傳參)的內容了,其實我們在從后台拿到數據遍歷后,每一個對應的id都會有,這里用的query:{id:item,id},其實就是把遍歷對應的id傳到path
對應的那個界面,這個常出現在列表頁到詳情頁頁這里(當然不只是這里了,其他地方用的很多很多)。
對於傳參的方式還是要說下的多余的:
query和params:
a.像這種:to="{path:'/editaddress',query:{ id:item.id }}是query進行傳值;這種:to="{path:'/editaddress',params:{ id:item.id }},兩種方式傳值沒什么差別,
但比如在詳情頁引入值時this.paramsid = this.$route.params.id ---->params引入;this.queryId = this.$route.query.Id---->query引入(當然用name也行)
對於需要進行安全保護的網站其實也可以在此處進行選擇params-->name(不顯示路徑如index/login)--->當然這只是相對query.-->path(顯示?后面帶的參數如index/login?id=1&&name=asd)安全的方法.
需要說明的這種方法在有的頁面刷新會丟失傳過來的數據,就是不太穩定。下面是另一個傳參的方法倒是可以解決這種問題,先看代碼:
request.get('shop/ce/' + this.product_id +'? num='+this.num ,{
id:this.product_id, num:this.num, }).then((response) => { if(response){ console.log(this.product_id) this.$router.push({path:'/order?pid='+this.product_id}) } }).catch((ex) => { console.log(ex.response) })
上面的request只是我封裝的一個axios請求方法(主要是方便,不多說),看紅線重點,這個地方的傳參其實是很優秀的,自己在定義一個變量接收id,因為是寫在跳轉路徑里面的,這樣在刷新時人家會一直帶着這個ID,數據自然就不會丟失了,在需要接受ID的頁面用
<div class="main" v-for="(item,index) in Unpaycontent" :key="index">
<div class="main_top">
<div class="imgContral">
<img :src="item.goods_image">
<div class="describtion"><a>待支付</a></div>
</div>
<div class="details"><p style="color:#000;">{{item.goods_name}}</p></div>
<div class="main_topright">
<p>{{item.price}}</p>
<p>×{{item.num}}</p>
</div>
<div class="top_bottom">
<span style="float:right;">合計:<a style="color:red;">{{item.total_price}}</a></span>
</div>
</div>
<div class="main_bot">
<a @click="click(item.id)">立即支付</a>
</div>
</div>
還是看紅線,因為我們在點擊的時候傳的有item.id,這就解決了傳不同ID的頭疼問題,在methods里用方法接受時隨便定義下改個好看的名字就能很好的把ID拿出來傳到后台了,為了展示的詳細點,還是貼一下代碼吧。
getallData (index) {
request.get('/shop/orders'+index, { }).then((response) => { }).catch((ex) => { }) },
這里的item.id就被我變成了index了,其他的就是愉快的給后台解決了。
本文主要是對傳參進行簡短總結下,如果有其他的好的傳參的方法或者本篇我寫的有錯的地方,歡迎指教!