javaScript

多个switch开关调用同一个接口,以及后端数据浅拷贝赋值

<template>
  <!-- 隐私 -->
  <div class="addme_type">
    <wx-sub-page :title="pageName" class="privacy">
      <div class="weui-cells__tips switch_tip">可通过以下方式搜索到我</div>
      <div class="group-info-page">
        <wx-cell-group>
          <!-- switch开关,操作值为:true/false-->
          <wx-cell
            title="ID号"
            isSwitch
            v-model="form.searchById"
            @input="switchHandle(form.searchById, 'searchById')"
          ></wx-cell>
          <wx-cell
            title="手机号"
            isSwitch
            v-model="form.searchByMobile"
            @input="switchHandle(form.searchByMobile, 'searchByMobile')"
          ></wx-cell>
        </wx-cell-group>

        <div class="weui-cells__tips">
          关闭后,其他用户将不能通过上述信息找到你
        </div>
        <div class="weui-cells__tips switch_tip">
          可通过以下方式添加我为好友
        </div>
        <wx-cell-group>
          <wx-cell
            title="群聊"
            isSwitch
            v-model="form.friendedByGroup"
            @input="switchHandle(form.friendedByGroup, 'friendedByGroup')"
          ></wx-cell>
          <wx-cell
            title="二维码"
            isSwitch
            v-model="form.friendedByQrcode"
            @input="switchHandle(form.friendedByQrcode, 'friendedByQrcode')"
          ></wx-cell>
        </wx-cell-group>
      </div>
    </wx-sub-page>
  </div>
</template>
<script>
import { gconstants } from '@/libs/gconfig';
export default {
  data() {
    return {
      pageName: '隐私',
      form: {
        friended: 1,
        searchById: 1,
        searchByMobile: 1,
        friendedByGroup: 1,
        friendedByQrcode: 1
      },
      direct: gconstants.direct
    };
  },
  methods: {
    // 浅拷贝直接赋值
    async init() {
      try {
        let res = await this.$api.self.userPrivacyInit(this.direct);
        return res.result ? Object.assign(this.form, res.result) : {};
      } catch (e) {
        console.log(e);
      }
    },
    // 对象创建
    strMapToObj(strMap) {
      let obj = Object.create(null);
      for (let [k, v] of strMap) {
        obj[k] = v;
      }
      return obj;
    },
    async switchHandle(checked, id) {
      let value = checked ? 1 : 0;
      let myMap = new Map().set(id, value); //根据传入的key创建对象 如:{searchById:1}
      const params = Object.assign(this.form, this.strMapToObj(myMap));
      try {
        let res = await this.$api.self.userPrivacy({ ...params }, this.direct);
        console.log(res);
      } catch (e) {
        console.log(e);
      }
    }
  },
  mounted() {
    this.init();
  }
};
</script>
上次更新: