【vue学习】


一、向服务器发请求时

export const reqGetSearchInfo = (params) =>
  requests({
    url: "/list",
    method: "post",
    data: params,
  });
  1. 由于当前函数要接受外部传递参数,这个接口,给服务器传递参数params,
  2. 调用函数的时候至少要是一个空对象,否则会报错
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 || [];
  },
};
  1. 当前形参state指的是当前仓库中的state,非大仓库中state。
  2. 假如没网服务器返回来的至少让它是个空数组 || [];
  3. 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 });
      }
    },
  1. 此处写undefined而不写空字符串,因为这个字段不会带给服务器
  2. 加if判断为了保留需要的的params参数(这样更严谨)
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值