vue 组件 key在渲染时的作用

50 阅读1分钟

遇见一个诡异的bug,封装的组件在请求完数据后页面并未更新,经过各种折腾发现是key的问题,在deviceType更改后会重新请求下拉框的options

            name: "机型",
            key: "machineType",
            type: "select",
            optionLabel: "label",
            optionValue: "value",
            options: async () => {
              const loading = this.$loading({
                lock: true,
                text: "Loading",
                spinner: "el-icon-loading",
                background: "rgba(0, 0, 0, 0.7)",
              });
              try {
                const res = await post("", {
                  deviceType: this.deviceForm.deviceType,
                });
                return res.data.machineType || [];
              } finally {
                loading.close();
              }
            },
            referTo: ["deviceType"],
            rules: [
              {
                required: true,
                message: "请选择机型",
                trigger: "change",
              },
            ],
            width: "18rem",
          },

现象是更改type后总是会显示上一次请求过来的数据,总是延后渲染一次,解决方式是增加动态key,在每次请求数据后都会让key的值改变


//请求部分
 const options = await field.getFn();
        this.$set(field, "options", options);
        this.renderKey++; // 改变 key 强制重新渲染
        
 //渲染部分
   field.type === "select"
                ? h(
                    "el-select",
                    {
                      key: field.key + "-" + this.renderKey,
                      props: {
                        value: this.form[field.key],
                        ...field.attributes,
                      },
                      ):null