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>