Changing vuejs mixin to vue3 composition API

I have a script that I need to convert to the Vue3 composition API. However, when attempting this conversion, I encountered several 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);
    }
  }
};

The attempt below includes issues with implementing props, watch, and compute.

The following snippet shows my attempts:

/**
 * 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 it in the setup method of CompA.vue.

 setup(){

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

Answer №1

defineProps is a unique feature of the script setup syntax in Vue 3, not to be confused with the composition API. It essentially acts as a macro that compiles to the `props` option and cannot be directly used within a composable function.

If you have a reactive prop that may change over time, it should be passed as a computed property to the composable function, like this:

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

To implement this, you would use it as follows:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Choose Default Value in Drop-Down List in AngularJS when Page Loads

Within the realm of Angularjs, there exists a DropDown: <select ng-model="category" ng-change="categoryChanged(category)" class="form-control" data-ng-options="category as category.name for category in categories"> <option value="">Se ...

The function Waterline.create() is not available

Currently in the process of building a basic REST API using Sails.js and Waterline-ORM, I've encountered an issue regarding Post.create is not a function when trying to create an object within the ORM on a Post request. Here is my model: module.expor ...

Updating the value of an Angular select on change is not being reflected

If the select element is changed, the value should be set to something different from what was selected. There's a feature in place that only allows 4 item types to be selected at a time; if more than 4 are chosen, the value reverts back to its origin ...

After updating to version 0.10.10, Visual Studio Code no longer recognizes JavaScript syntax highlighting

Can anyone help me with this issue? I have attached a screenshot for reference. Any assistance would be greatly appreciated. https://i.sstatic.net/3cjKc.png ...

Issue: Attempting to access the property 'then' of an undefined entity causes a TypeError. However, the code executes

Here's an unusual situation. I am working with Vue.js connected to a php backend, and I have the following code snippet: validateEmail(){ if(!this.emailModel.loading && this.$refs.emailForm.validate()) ...

Ways to resolve - Error: Unable to access 'comments' property of null

I am currently working on developing a blog web application and I am facing an issue with enabling user comments on posts. Despite extensive research and attempts to troubleshoot by searching online, I have not been able to find a solution. I have been str ...

Displaying a collection of nested objects in AngularRendering a group

Is there a way to render an object of objects in Angular without converting it into an array or similar structure? I have a large object of objects and I want to avoid multiple iterations through object-to-array conversions just to loop through the array i ...

An error occurred while trying to access the object null in React-Native, specifically when evaluating 'this.state.token'

I encountered an error while trying to execute a class in a view: When running the class, I received the following error message: null is not an object (evaluating 'this.state.token') The problematic class that I'm attempting to render: c ...

Javascript is not fetching the value

Here is the code snippet I am working with: var categoryDetailId = $("#createEventForm-categoryDetail-idCategory").val(); and this link from my rendered page: After clicking the button, it returns NaN Update: I tried setting it manually, but it still ...

How can resolvers in GraphQL optimize data fetching based on necessity?

I am working with two unique GraphQL types: type Author { id: String! name: String! } type Book { id: String! author: Author! name: String! } Within my database structure, there exists a foreign key inside the books table: table authors (pseu ...

Storing/Caching API Requests with NUXT.JS

I am in the process of developing a NUXT.JS application that retrieves JSON data from an API called Storyblok. I would appreciate some advice or suggestions on how to efficiently store/cache the API response to avoid making multiple requests when navigatin ...

The most effective method for creating a native mobile app (for iOS, Android, and more) is by utilizing an existing AngularJS

I developed a cutting-edge AngularJS application utilizing various plugins like angular ui-router, angular-translate, and bootstrap 3. While the app runs smoothly on web browsers of desktops/laptops and smartphones with built-in browsers, I have concerns ...

Data is successfully being stored in an array in AngularJS, however, it is not appearing in the user interface

Having an issue with displaying updated data on my UI. I am successfully pushing data into the database and an array using Angular 2-way binding. The data is being pushed as confirmed by the console, but it's not showing up on the user interface. Con ...

Update the value of v-model without altering the underlying data

Recently, I've been working with some interesting data: data: () => ({ items: [ { id: 1, name: "Item 1", price: 2, quantity: 5 }, { id: 2, name: "Item 2", price: 3, quantity: 6 } ] }) In my template, I h ...

While working on my Laravel and Vue.js project, I encountered the following error message: "Module not found: Error: Can't resolve './vue/app' in 'C:vue odolist esourcesjs'"

Running into an issue where the app.vue file cannot be found in the app.js. I'm using Laravel version "8.31.0" and VueJS version "^2.6.12". Any assistance would be highly appreciated. The content of app.js is: require('./bootstrap'); impor ...

Encountered Runtime Error: TypeError - Carousel triggering issue with reading properties of null (specifically 'classList') in Tailwind Elements

Currently, I am encountering the error message: Unhandled Runtime Error TypeError: Cannot read properties of null (reading 'classList') while utilizing the Carousel component. The problem arises when I attempt to populate the carousel with images ...

Using TypeScript, Electron can easily share a constants file between both main and renderer processes

Can Electron with Typescript share a constants.ts file between the main and renderer processes? Folder Structure: src/ main main.ts renderer renderer.ts shared constants.ts //constants.ts export const constants= { foo: '123' bar ...

Access the Fetch API endpoint located within the /app directory in the Next JS version 13

Currently, I am in the process of developing an API and fetching data within Next JS 13. I recently came across this query: How do you put api routes in the new app folder of Next.js? After researching, I have come up with the following scripts: /src/app ...

Tips for controlling frustum in three.js

Recently, I came across a fascinating parallax view implementation that creates an illusion of depth, and now I'm eager to recreate something similar using Three.js. One hurdle I've encountered is the need for a non-symmetric camera frustum. Ess ...

How can we use forEach on an array or JSON data while sorting by the most recent date?

How can I reverse the order of data in the "forEach" loop so that the latest date is displayed first instead of the oldest to newest? var json = { // JSON data goes here } json.TrackingRecord.MovementInformation.Movement.reverse().forEach(function(it ...