Search code examples
javascriptvue.jsvue-componentvuejs3vue-composition-api

Convert vuejs mixin to vue3 composition API


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
      }
  },

Solution

  • 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))