You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将VueJS Mixin转换为Vue3 Composition API遇问题求助

Vue2 Mixin 转 Vue3 Composition API 正确转换方案

以下是原Vue2 Mixin代码、我尝试编写的错误Composition API代码及组件引入方式,求正确转换方案:

原Vue2 Mixin代码

export default {
  props: {
    field: {
      type: Object,
      required: true
    },
    formValues: {
      type: Object,
      required: true
    },
    debug: {
      type: Boolean,
      required: false
    }
  },
  data() {
    return {
      fieldValue: '' // 本地存储字段值
    };
  },
  watch: {
    fieldValue: {
      immediate: true,
      handler() {
        // 本地字段值变化时触发验证
        this.$emit("form-data",
          {
            key: this.field.key,
            value: this.fieldValue,
          },
        )
      }
    }
  },
  computed: {
    showFeild() {
      if (this.field.showIf == undefined) {
        // 检查是否存在可见性配置
        return true;
      }
      try {
        console.log("showExpression ", this.formValues);
        // eslint-disable-next-line no-unused-vars
        var form = this.formValues;
        var res = eval(this.field.showIf);
        return res;
      } catch (e) {
        console.error("请修正表达式 ", this.field.showIf, "对应字段 ", this.field.key);
        return true;
      }
    },
    validateField() {
      if (this.field.required && (!this.fieldValue || this.fieldValue.trim() === '')) {
        return false;
      }
      // 可添加更多验证规则
      return true;
    }
  },
  methods:{
    validate(){
        console.log("正在验证..",this.field.key);
    }
  }
};

我尝试的错误Composition API代码

/**
 * 文件名: Template.js 使用Composition API
 * 存在多处错误
 */

import { ref, computed ,defineProps} from "vue";

export default function () {


    const fieldValue = ref(0);
    const props = defineProps({
        field: Object
      })

    // 监听字段值
    const showFeild = computed(() => {
        if (props.field.showIf == undefined) {
            // 检查是否存在可见性配置
            return true;
        }
        try {
            console.log("showExpression ", this.formValues);
            // eslint-disable-next-line no-unused-vars
            var form = this.formValues;
            var res = eval(props.field.showIf);
            return res;
        } catch (e) {
            console.error("请修正表达式 ", props.field.showIf, "对应字段 ", props.field.key);
            return true;
        }
    });

    const validateField = computed(() => {
        if (props.field.required && (!props.fieldValue || props.fieldValue.trim() === '')) {
            return false;
        }
        // 可添加更多验证规则
        return true;
    });


    return {
        fieldValue,
        showFeild,
        validateField,
        props
    }
}

组件引入方式

import useComp from './Template.js'

setup(){
      const {fieldValue,showFeild,validateField} = useComp()
      return{
        fieldValue,showFeild,validateField
      }
  },

正确的转换方案

1. 修复后的Composition API代码

import { ref, computed, watch, defineProps, defineEmits } from "vue";

export default function () {
    // 完整定义原Mixin中的所有props
    const props = defineProps({
        field: {
            type: Object,
            required: true
        },
        formValues: {
            type: Object,
            required: true
        },
        debug: {
            type: Boolean,
            required: false,
            default: false
        }
    });

    // 定义emit事件,替代原Mixin的$emit
    const emit = defineEmits(["form-data"]);

    // 初始化fieldValue为字符串,匹配原data的初始值
    const fieldValue = ref('');

    // 监听fieldValue,实现原watch的逻辑
    watch(fieldValue, () => {
        emit("form-data", {
            key: props.field.key,
            value: fieldValue.value
        });
    }, { immediate: true });

    // 实现原showFeild计算属性
    const showFeild = computed(() => {
        if (props.field.showIf == undefined) {
            return true;
        }
        try {
            console.log("showExpression ", props.formValues);
            // 直接使用props.formValues替代this.formValues
            const form = props.formValues;
            const res = eval(props.field.showIf);
            return res;
        } catch (e) {
            console.error("请修正表达式 ", props.field.showIf, "对应字段 ", props.field.key);
            return true;
        }
    });

    // 实现原validateField计算属性
    const validateField = computed(() => {
        if (props.field.required && (!fieldValue.value || fieldValue.value.trim() === '')) {
            return false;
        }
        // 可添加更多验证规则
        return true;
    });

    // 实现原validate方法
    const validate = () => {
        console.log("正在验证..", props.field.key);
    };

    return {
        fieldValue,
        showFeild,
        validateField,
        validate
    };
}

2. 组件引入调整(若需调用validate方法需一并返回)

import useComp from './Template.js'

setup(){
      const {fieldValue, showFeild, validateField, validate} = useComp()
      return{
        fieldValue, showFeild, validateField, validate
      }
  },

错误点说明

  • 未完整定义props:遗漏了原Mixin的formValues和debug属性
  • 错误使用this:Composition API中不能通过this访问props,需直接用props.xxx
  • fieldValue初始化错误:原代码初始值为字符串'',错误代码写成了数字0
  • 未定义emit:原Mixin的$emit需用defineEmits定义后才能使用
  • 缺失监听逻辑:错误代码未实现原Mixin中watch fieldValue的功能
  • validateField引用错误:错误使用props.fieldValue,应直接访问fieldValue.value
  • 缺少原Mixin的validate方法

内容的提问来源于stack exchange,提问作者Hexgear

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 10:07:45