vue獲取后台數據列表並在頁面遍歷顯示


1.在home.js中設置url

var home = {
searchByVender:'/index/search', //首頁搜索-商家和商品列表
}

2.引入home.js

import home from "@/common/api/home"

3.在data中定義關鍵字和搜索返回的商品列表

data() {
return {
keyword: '', //搜索關鍵字
searchShops: [], //搜索返回的商品
}
},

4.在生命周期函數中調用搜索函數

mounted() {
this.getShops();
},

  或者在methods中調用search函數

search() {
const keyword = this.keyword.trim()
this.getShops(keyword);
},

5.在搜索頁面通過關鍵字獲取商品(getShop方法)

getShops(keyword) {
const vm = this;
const url = home.searchByVender;
const params = "?schoolId=1&keywords=" + keyword;
// 記錄搜索歷史
this.$store.dispatch('saveSearchShopHis', keyword);
vm.axios.get(url + params).then((response) => {
Indicator.close();
let results = (response.data && response.data.results) || [];
if (results && results.length > 0) {
// 獲取搜索到的商品
vm.searchShops = results;
} else {
// 沒有搜索到商品
// 展示熱搜
this.isShowSearch = true;
// 將之前搜索到的商品置為空
vm.searchShops = [];
// 將關鍵字置空
vm.keyword = "";
Toast({
message: '沒找到合適的商品或商家',
position: 'middle',
duration: 1000
});
}
}, (response) => {
Indicator.close();
Toast({
message: '數據獲取失敗,請重試',
position: 'middle',
duration: 1000
});
});
},

6.在頁面中渲染出來

<ul>
<li v-for="(shops, index) in searchShops">
<div class="searchResultShop">
<img class="searchResultShopImg" :src="shops.imagePath">
<a class="searchResultShopName">{{shops.name}}</a>
</div>
<div class="searchResultGoods">
<a class="searchResultGoodsItem" v-for="(shop, index) in shops.goods">
<img class="searchResultGoodsImg " :src="shop.imagePath"/>
<p class="searchResultGoodsPrice">{{shop.name}}¥{{shop.price}}</p>
</a>
</div>
</li>
</ul>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM