AdaKing88
2023-08-23 9cad48db6c56c3e2796a9d6da881817ef13b6eca
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
<template>
  <el-switch
    v-model="init_data.value"
    :loading="init_data.loading"
    :before-change="handlerSwitch"
  >
  </el-switch>
</template>
 
<script>
import { reactive, getCurrentInstance, watch } from "vue";
// requestUrl
// import ApiUrl from "@/api/requestUrl";
//API
// import { SwitchStatus } from "@/api/common";
export default {
  name: "SwitchComponent",
  props: {
    data: {
      type: Object,
      default: () => ({}),
    },
    config: {
      type: Object,
      default: () => ({}),
    },
  },
  emits: ["update:value", "callback"],
  setup(props) {
    // 配置信息
    const config = reactive(props.config);
    // 数据
    const data = reactive(props.data);
    // 初始值
    const init_data = reactive({
      value: data[config.prop],
      loading: false,
    });
    // 监听数据
    watch(
      () => props.data,
      (newValue, oldValue) => {
        init_data.value = newValue[config.prop];
      }
    );
    // 获取实例上下文
    const { proxy } = getCurrentInstance();
    // 事件
    const handlerSwitch = (value) => {
      init_data.loading = true;
      // 请求参数
      const url =
        config.api_url || ApiUrl?.[config.api_module]?.[config.api_key]?.url;
      const method =
        config.method ||
        ApiUrl?.[config.api_module]?.[config.api_key]?.method ||
        "post";
      if (!url) {
        console.log("请求接口不存在");
        return false;
      }
      // 请求参数
      const key_id = config.key_id || "id";
      const request_data = {
        url,
        method,
        data: {
          [key_id]: data[key_id], // 等价于["id"]: data["id"]
          [config.prop]: !init_data.value, // 等价于["status"]: value
        },
      };
      return new Promise((resolve, reject) => {
        // SwitchStatus(request_data)
        //   .then((response) => {
        //     proxy.$message.success(response.message);
        //     data.status = value;
        //     init_data.loading = false;
        //     resolve(true);
        //   })
        //   .catch((error) => {
        //     init_data.loading = false;
        //     reject(false);
        //   });
      });
    };
    return { config, init_data, handlerSwitch };
  },
};
</script>