将Vue.js mixin转换为Vue 3的组合式API。

huangapple go评论64阅读模式
英文:

Convert vuejs mixin to vue3 composition API

问题

I've translated the code you provided from English to Chinese:

我有一个脚本需要转换成vue3的组合API
尝试将其转换为组合API结果出现了许多错误

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) {
        // 检查是否存在visible属性
        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);
    }
  }
};

我尝试了下面的代码,但在实现props、watch和compute时遇到了问题。

下面的片段是我正在做的事情。

/**
 * 文件名:Template.js 使用组合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) {
            // 检查是否存在visible属性
            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方法中使用它。CompA.vue。

setup(){

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

希望这个翻译对你有所帮助。如果需要进一步的帮助,请随时提问。

英文:

I have script. which i need to convert to vue3 composition API.
Tried to convert this to compoistion API, resulting in many errors

export default {
  props: {
    field: {
      type: Object,
      required: true
    },
    formValues: {
      type: Object,
      required: true
    },
    debug: {
      type: Boolean,
      required: false
    }
  },
  data() {
    return {
      fieldValue: '' // Store the field value locally in the component
    };
  },
  watch: {
    fieldValue: {
      immediate: true,
      handler() {
        // Trigger validation when the local field value changes
        this.$emit("form-data",
          {
            key: this.field.key,
            value: this.fieldValue,
          },
        )
      }
    }
  },
  computed: {
    showFeild() {
      if (this.field.showIf == undefined) {
        //check if visible is present or not
        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("Please fix expression ", this.field.showIf, "for ", this.field.key);
        return true;
      }
    },
    validateField() {
      if (this.field.required && (!this.fieldValue || this.fieldValue.trim() === '')) {
        return false;
      }
      // Add more validation rules as needed
      return true;
    }
  },
  methods:{
    validate(){
        console.log("validating..",this.field.key);
    }
  }
};

I tried with below code but having problem implementing the props, watch, compute.
> The below snippet is of what I was doing.

/**
 * FileName: Template.js With Composition API
 * this has multiple errors
 */

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

export default function () {


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

    //watch feild value
    const showFeild = computed(() => {
        if (props.field.showIf == undefined) {
            //check if visible is present or not
            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("Please fix expression ", props.field.showIf, "for ", props.field.key);
            return true;
        }
    });

    const validateField = computed(() => {
        if (props.field.required && (!props.fieldValue || props.fieldValue.trim() === '')) {
            return false;
        }
        // Add more validation rules as needed
        return true;
    });


    return {
        fieldValue,
        showFeild,
        validateField,
        props
    }
}

I am importing this into another component by.
import useComp from './Template.js'
and using this in the setup method. CompA.vue.

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

答案1

得分: 0

defineProps不是组合API,而是script setup语法的宏,它编译为props选项,不能在可组合中使用。

如果一个prop是响应式的并且可以随时间变化,它需要作为计算属性传递给可组合:

function useComp(field, formValues) {
  ...
  try {
    console.log("showExpression", unref(formValues));
    ...
  } catch (e) {
    console.error("Please fix expression", unref(field).showIf, "for", unref(field).key);
    ...
  }
  ...
}

并且像这样使用:

useComp(computed(() => props.field), computed(() => props.formValues))
英文:

defineProps is not composition API but a macro for script setup syntax that compiles to props option, it cannot be used in a composable.

In case a prop is reactive and can change over time, it needs to be passed as a computed to the composable:

function useComp(field, formValues) {
...
try {
console.log("showExpression ", unref(formValues));
...
} catch (e) {
console.error("Please fix expression ", unref(field).showIf, "for ", unref(field).key);
...
}
...
}

And used like:

useComp(computed(() => props.field), computed(() => props.formValues))

huangapple
  • 本文由 发表于 2023年4月13日 20:51:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/76005655.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定