Ensuring the integrity of object formats in vue.js

Currently, I am working on a component using vue.js and facing a slight issue. The component has a wide range of parameters, so to keep things organized, I opted for the approach outlined below:

<script type="text/javascript">
    Vue.$noClientConf = {
    'cmp_name':         'NoClient', 
    'cmp_title':        'Selection du client',
    'url':              'ajax/getclients.php',
    'parent':           null,
    'opt_texte':        'NomClientFR',
    'opt_valeur':       'NoClient',
    'cmp_max_options':  3,
    'opt_custom':       null,
    'data_size':        10,
    'data_style':       'btn btn-default btn-sm',
    'data_live_search': 'true'
    };
</script>

<div id="app">

  <div class="col-lg-2">
    <flex-select ref="NoClient" :conf="Vue.$noClientConf"></flex-select>
  </div>

</div>

<script type="text/javascript">
    var app = new Vue({
      el: "#app",
      data:{Vue}
    });
</script>

In essence, I create an object with the necessary parameters and pass it to my component. However, I would like to set default values for some of these parameters to simplify the process for users.

I have researched Vue.js props validation and believe it aligns well with my goals. However, it appears that while you can validate if a prop is an object, you cannot validate its structure. For instance, I wish to achieve something like:

props: {
        config.cmp_name: {
            type:String,
            required: true
        },
        config.cmp_title:{
            type:String,
            required: true
        }
    }

So my query is essentially... is there a way to accomplish the above?

Answer №1

Utilize the object binding syntax.

<flex-select ref="NoClient" v-bind="defaults"></flex-select>

This method will transfer all the attributes of defaults and only validate the ones required.

props: {
  cmp_name: {
    type:String,
    required: true
  },
  cmp_title:{
    type:String,
    required: true
  }
}

Alternatively, you can implement a function as a custom validator.

props:{
  conf: {
    validator(config){
      let cmp_name = config.cmp_name && typeof config.cmp_name === "string"
      let cmp_title = config.cmp_title && typeof config.cmp_title === "string"
      return cmp_name && cmp_title
    }
  }
}

As a side note, I encountered difficulties making use of Vue.$noClientConf in an example. Hence, I opted to create a defaults object instead.

console.clear()

const defaults = {
  'cmp_name':         'NoClient', 
  'cmp_title':        'Client Selection',
  'url':              'ajax/getclients.php',
  'parent':           null,
  'opt_texte':        'ClientNameEN',
  'opt_value':        'NoClient',
  'cmp_max_options':  3,
  'opt_custom':       null,
  'data_size':        10,
  'data_style':       'btn btn-default btn-sm',
  'data_live_search': 'true'
};

Vue.component("flex-select",{
  props: {
  cmp_name: {
    type:String,
    required: true
  },
  cmp_title:{
    type:String,
    required: true
  }
},
  template:`
    <div>{{cmp_name}} {{cmp_title}}</div>
  `
})

new Vue({
  el:"#app",
  data:{
    defaults
  }
})
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="781d1e0e5b393f333b">[email protected]</a>/dist/vue.js"></script>
<div id="app">
  <flex-select v-bind="defaults"></flex-select>
  {{defaults}}
</div>

Answer №2

To implement a custom validator, it is recommended to utilize the Set() object.

For instance:

Define the object required by the ExampleComponent component:

const obj = {
    block1: {
      icon: 'example',
      title: 'example',
      content: 'example'
    },
    block2: {
      icon: 'example',
      title: 'example',
      content: 'example'
    }
  };

Here is the component with a custom validator:

export default {
    name: 'ExampleComponent',
    props: {
      data: {
        type: Object,
        validator: (o) => {
          const set = new Set();
          set.add(!!(o.block1 && o.block1.icon && typeof o.block1.icon === 'string'));
          set.add(!!(o.block1 && o.block1.title && typeof o.block1.title === 'string'));
          set.add(!!(o.block1 && o.block1.content && typeof o.block1.content === 'string'));
          set.add(!!(o.block2 && o.block2.icon && typeof o.block2.icon === 'string'));
          set.add(!!(o.block2 && o.block2.title && typeof o.block2.title === 'string'));
          set.add(!!(o.block2 && o.block2.content && typeof o.block2.content === 'string'));
          return !set.has(false);
        },
      },
      color: {
        type: String,
        validator: value => ['black', 'white'].includes(value),
      },
    },
  };

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

Is there a method to verify the consumability of an API without having to make a direct request to it?

I'm working on an idle timer feature where the API will be called to update data once the timer runs out. How can I check if the API is still usable without actually sending a request? ...

Is there a way to establish a condition for an onSubmit event?

I have a form that I'm working on, and I would like for an error message to pop up upon the first onSubmit, and then function normally on subsequent submissions. Here is the current setup: const [submitting, setSubmitting] = useState(false); const ha ...

Ways to repair the error message: "Unable to access property 'clientWidth' of undefined"

Whenever I resize the window, I encounter an error stating "Cannot read property 'clientWidth' of null". It appears to be related to the fact that the ref is null. Do you have any suggestions on how to troubleshoot this issue? import React, { us ...

Hierarchy-based dynamic breadcrumbs incorporating different sections of the webpage

Currently in the process of developing a dynamic breadcrumb plugin with either jQuery or Javascript, however I am struggling to implement functionality that allows it to change dynamically as the page is scrolled. The goal is to have a fixed header elemen ...

Receive a notification for failed login attempts using Spring Boot and JavaScript

Seeking assistance with determining the success of a login using a SpringBoot Controller. Encountering an issue where unsuccessful logins result in a page displaying HTML -> false, indicating that JavaScript may not be running properly (e.g., failure: f ...

Connection to Mysql database terminated for Node.js

I'm currently working on integrating a basic form into my database to enhance my understanding of node.js. However, I keep encountering an intriguing error during the process... error when connecting to db: { [Error: Connection lost: The server close ...

Storing data values from a specific object key into an array in Vue: Step-by-step guide

Just dipping my toes into the world of Vue framework here. I managed to create a selectable table that stores data in an object. I want this function to run in the background, so I figured it should be in the computed section. The object structure is as fo ...

Documentation guide: best practices for indicating optional return values

I am tasked with properly documenting a function using JSDoc. The function triggers something if it returns true, otherwise it does not. However, the return value must always be of boolean type. Here is my proposed JSDoc documentation: * @return {boolean ...

How does JavaScript function syntax differ in Next.js and JSX?

I'm in the process of creating a function that allows users to select different sizes. It currently works fine with just JavaScript and HTML, but I'm encountering an error when using it in Next.js. Can someone confirm if my syntax for the JavaScr ...

Load Jquery Ajax every second interval

I discovered this script on the W3 school website. <script> $(document).ready(function(){ setInterval(function(){ $("#div1").load("demo_test.txt"); }, 30000); // Load demo_test.txt every 30 seconds }); </script> The purpose of ...

Conceal the form node's visibility upon initial inspection

My goal is to understand how the "add a comment" feature on Stack Overflow works by examining the code in three sections: footnote-list, footnote-form, and add-form-link. footnote-list footnote-form add-form-link <div class="col-md-12 footnotes"> ...

AngularJS - real-time validation using the $valid property

I have implemented AngularJS to handle form validation and submission. The submit button is configured as follows: <button type="submit" ng-disabled="btn" ng-click="submit(settings.$valid)" class="btn btn-primary"> Submit </button> The butt ...

Scrolling animations tailored to the navbar using jQuery

My fixed header contains a few links, and I've written some code that almost works perfectly. The issue is that there's a delay when the second function is executed. While it successfully scrolls to the top of the page when the linked element is ...

In React, when a user clicks the back button on the browser window, ensure you pass props back to the originating component

While moving from component A to component B through routing, I want to send a prop back to A when the user clicks on the browser's back button while on B. Can this be achieved? I am currently using React's history.push for navigating between com ...

WebStorm not recognizing NodeJS Core Modules in External Libraries

As a newcomer to NodeJS and WebStorm, I am currently diving into a tutorial on creating an Express app. In the tutorial, the instructor always gets prompted with "Configure NodeJS Core Module Sources" including the URL nodeJS.org when creating a new NodeJ ...

A messaging application powered by socket.io and the Express JS framework

I am currently learning Node.js and I am encountering an issue with using socket.id to identify logged in users on the client side using their email id and password. The verification process happens on the server side, and if successful, the user's so ...

Is there a hover function in jQuery that works with both mouseenter and mouseout events?

I've been facing a slight issue with a list of items using the <li> element. I have a plugin running that dynamically adds a data-tag ID to the data-* attribute of these items. As a result, all items are dynamically added and another function I ...

jQuery script located on local server fails to function

After downloading the jQuery.js file from jQuery.com, I made sure to save it in multiple locations - including JRE/Lib and my desktop where the HTML file that calls it is located. The script reference looks like this: <head> <script type= ...

Validation in Ajax Response

When receiving an object from my API call, I want to perform error checking before displaying the JSON data in my view. function response(oResponse) { if (oResponse && oResponse != null && typeof oResponse === "object" && oResponse.response ...

How can I locate the element immediately preceding $(this)?

Struggling to retrieve the value of the $(.subname) when the .bigadminbutton is clicked and calling the updateSub() function. I have tried various methods like prev, sibling, parent, children, find, but none seem to work. This minor task is taking up too ...