一、向服务器发请求时
export const reqGetSearchInfo = (params) =>
requests({
url: "/list",
method: "post",
data: params,
});
- 由于当前函数要接受外部传递参数,这个接口,给服务器传递参数params,
- 调用函数的时候至少要是一个空对象,否则会报错
import { reqGetSearchInfo } from './api'
console.log(reqGetSearchInfo({}))
此处用户派发actions时,第二个参数params传过来的至少是一个空对象。
const actions = {
async SearchInfo({ commit },params={}) {
let result = await reqGetSearchInfo(params);
// console.log(result, "11111111111");
if (result.code == 200) {
commit('SEARCHINFO',result.data)
}
},
};
二、getters
1.注意事项
const getters = {
goodsList(state) {
return state.SearchInfo.goodsList || [];
},
attrsList(state) {
return state.SearchInfo.attrsList || [];
},
trademarkList(state) {
return state.SearchInfo.trademarkList || [];
},
};
- 当前形参state指的是当前仓库中的state,非大仓库中state。
- 假如没网服务器返回来的至少让它是个空数组 || [];
- mapGetters获取数据时,还是要给它派发。不然获取不到数据(今天一个bug就是这样)
mounted(){
this.$store.dispatch("SearchInfo", {})
},
如果页面请求要发多次,则可以封装成一个函数,在需要的时候调用。
methods: {
getData() {
this.$store.dispatch("SearchInfo", this.searchParams);
},
mounted() {
this.getData();
},
2.合并参数
Object.assign(this.searchParams, this.$route.query, this.$route.params);
可将后两个参数合并到第一个中
三、监听路由变化请求数据
watch: {
$route() {
Object.assign(this.searchParams, this.$route.query, this.$route.params);
this.getData();
this.searchParams.category1Id = "";
this.searchParams.category2Id = "";
this.searchParams.category3Id = "";
},
},
$route前不用加this
,为什么?$route和data中的数据同级,以前监听data中的数据不用this,这里监听 $route也不用加this。
四、面包屑
把服务器参数值置空,并且发请求
removeCategoryName() {
this.searchParams.categoryName = undefined;
this.searchParams.category1Id = undefined;
this.searchParams.category2Id = undefined;
this.searchParams.category3Id = undefined;
this.getData();
// this.$router.push({ name: "search" })
if (this.$route.params) {
this.$router.push({ name: "search", params: this.$route.params });
}
},
- 此处写undefined而不写空字符串,因为这个字段不会带给服务器
- 加if判断为了保留需要的的params参数(这样更严谨)