Tips on removing v-bind directives from HTML code in VueJS

So, I've been working with Vue code and HTML recently.

Take a look at this example:

Vue.component('area-selectors-box', {
  template: `
    <div class="area-selectors-box">
      <area-selector v-for="(select, index) in selects" :select="select" :key="index"></area-selector>
    </div>
  `,
  props:['selects']
});

When I inspect the page source, I notice the v-bind:selects="selects" part, which I believe is not compliant with standards.

Other components have similar issues with object properties, like:

Vue.component('area-option', {
  template: `<option :area="area" :value="area.term_id">{{area.name}}<slot></slot></option>`
  ,props: ['area']
});

This results in output like:

<option area="[object Object]" value="82">Europa</option>

which is not ideal.

Does anyone know how I can bind these properties without them displaying as attributes in the DOM?

Answer №1

Typically, when v-bind comes across a binding name that doesn't match a property on the target, the value is transformed into a string and set as an attribute. Because <option> doesn't have a property called area, the object is assigned as a string attribute, which can be seen in the DOM.

To ensure it's always assigned as a property, you can utilize v-bind's .prop modifier:

<option :area.prop="area" ...>

Vue.component('area-selectors-box', {
  template: `
    <div class="area-selectors-box">
      <area-selector v-for="(select, index) in selects" :select="select" :key="index"></area-selector>
    </div>
  `,
  props:['selects']
});

Vue.component('area-selector', {
  template: `<div>
    <select v-model="selection">
      <area-option
         v-for="option in select.options"
         :key="option.id"
         :area="option.area" />
    </select>
    <pre>{{selection}}</pre>
</div>`,
  props: ['select'],
  data() {
    return {
      selection: null,
    }
  }
})

Vue.component('area-option', {
  template: `<option :area.prop="area" :value="area.term_id">{{area.name}}<slot></slot></option>`
  ,props: ['area']
});

new Vue({
  el: '#app',
  data: () => ({
    selects: [
      { id: 1, options: [
                { id: 10, area: { term_id: 100, name: 'Europe' } },
                { id: 11, area: { term_id: 101, name: 'Asia' } },
              ]
      },
      { id: 2, options: [
                { id: 20, area: { term_id: 200, name: 'North America' } },
                { id: 21, area: { term_id: 201, name: 'South America' } },
              ]
      },
    ]
  }),
})
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="681e1d0d285a465e465958">[email protected]</a>"></script>

<div id="app">
  <area-selectors-box :selects="selects"></area-selectors-box>
</div>

Answer №2

Remember to always pass props when calling the component, rather than within the component itself. This approach ensures clean and functional HTML:

Here is an example of in-page HTML:

<!-- Make sure to pass selects to the area-selectors-box component -->
<div is="area-selectors-box" :selects="selects"></div>

Here is the JavaScript:

Vue.component('area-selectors-box', { // Passing select to area-selector
  template: `
    <div class="area-selectors-box">
      <area-selector v-for="(select, index) in selects" :select="select" :key="index"></area-selector> 
    </div>
  `,
  props:['selects']
});

Vue.component('area-selector', { // Passing area to area-option
  template: `
    <select @change="selected" >
      <option disabled selected value="">Select continent</option>
      <area-option v-for="area in select.areas" :area="area" :key="area.term_id"></area-option>
    </select>
  `,
  props:['select']
});

Vue.component('area-option', { // No props passed
  template: `<option :value="area.term_id">{{area.name}}<slot></slot></option>`
  ,props: ['area']
});

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

Display a few HTML elements sourced from a different online platform

I am trying to extract a specific value from a span element on another website and render it on my own website using either a GET/FETCH request or some other method. Currently, I have this code but I am struggling to extract the data I need. The data I am ...

Updating multiple subdocuments with Mongoose

My goal is to update a specific subdocument called addresses (which is working fine) and then update all other subdocuments except the one that was just changed. Whenever an address is changed to have is_preferred set to true, I need to update the previous ...

Exploring the World of Vue.js Object Imports

I am currently encountering an issue involving the importing of Objects from App.vue into a component. To provide context, this project consists of a Navigation Drawer component and an App.vue file. The Navigation Drawer contains Vue props that can be dyna ...

Encountering an error message stating "Unable to read property 'map' of undefined while attempting to create drag and drop cards

I have incorporated the library available at: https://github.com/clauderic/react-sortable-hoc The desired effect that I am aiming for can be seen in this example: https://i.stack.imgur.com/WGQfT.jpg You can view a demo of my implementation here: https:// ...

How can you loop through keys and values in a JSON object using JavaScript?

I am attempting to cycle through the JSON data below: { "VERSION" : "2006-10-27.a", "JOBNAME" : "EXEC_", "JOBHOST" : "Test", "LSFQUEUE" : "45", "LSFLIMIT" : "2006-10-27", "NEWUSER" : "3", "NEWGROUP" : "2", "NEWMODUS" : "640" } The keys in this JSON are d ...

Issue encountered when attempting to make a global call to an asynchronous function: "The use of 'await' is restricted to async functions and the top level bodies of modules."

As I embark on solving this issue, I want to point out that while there are similar questions on SO based on the title, upon close examination, they seem more intricate than my specific situation. The explanations provided in those threads do not quite ali ...

Spinning divs using JavaScript when the mouse hovers over them, and then returning them to their original position when the mouse moves

I am looking to create a functionality where a div rotates when the mouse enters it and returns to its original position when the mouse leaves. Everything works fine when interacting with one div, but as soon as I try hovering over other divs, it starts gl ...

The problem arises when using `$state.go` as it does not properly transfer the value to `$stateParams`

Within componentA, I am using an angular code: $state.go('home', {selectedFilter: "no_filter"}); In componentB, I have the following code: if ($stateParams.selectedFilter === 'no_filter') However, I am encountering an issue where $s ...

Is it possible to combine several m3u8 files into a single m3u8 file?

I am looking to consolidate multiple m3u8 files into a single file for seamless playback in one video player. How can I achieve this without compromising the individual clips? For instance, if I have zebra.m3u8, giraffe.m3u8, and lion.m3u8 files, is it pos ...

If the condition is true, apply a class with ng-class when ng-click is triggered

I am facing a situation similar to toggling where I am adding the class col-xs-6 to divide the page into two views. Initially, when I click, I set a variable value as true and in ng-class, I check for a condition to append the col-xs-6 class. Below is the ...

Retrieve new data upon each screen entry

After running a query and rendering items via the UserList component, I use a button in the UserList to run a mutation for deleting an item. The components are linked, so passing the deleteContact function and using refetch() within it ensures that when a ...

When using Vue computed, an error is thrown stating "Issue in rendering: 'InternalError: too much recursion'" if the same key is referenced in computed

As a newcomer to Vue, I wanted to track how many times a function in the computed section gets called. To achieve this, I created the following component: const ComputedCounter = { name: "ComputedCounter", template: ` <span>{{ value } ...

Looking to transform a PHP output value

I have a form with checkbox input, and a hidden 'sibling' input attached to it, in order to generate values of either '0' or '3' based on the checkbox status. When unchecked, the value is '0', and when checked, the ...

Revise the "Add to Cart" button (form) to make selecting a variant mandatory

At our store, we've noticed that customers often forget to select a size or version before clicking "Add to Cart" on product pages, leading to cart abandonment. We want to add code that prevents the button from working unless a variant has been chosen ...

Tips for modifying the audio session category in iOS using React Native

When using React Native, I know that to allow background audio playback (especially for react-native video), I need to adjust the audio session as outlined here in the Apple development documentation. However, I'm unsure of where to integrate the Obj ...

Need help inserting an image into the div when the ngif condition is true, and when the ngif condition is false

Essentially, I have a situation where I am using an *ngIf condition on a div that also contains an image. This is for a login page where I need to display different versions based on the type of user. However, I'm facing an issue where the image does ...

What is the best way to vertically align an InputLabel within a MUI Grid item?

I'm trying to vertically center the InputLabel inside a MUI Grid item. Here's what I've attempted: import { FormControl, Grid, Input, InputLabel, TextField } from "@mui/material"; export default function App() ...

Steps for closing the menu by clicking on the link

My issue with the menu on the landing page is that it only closes when clicking the cross button. I want it to close when any link from the menu is clicked. I attempted to add code using querySelector, but it only worked for the home link and not the other ...

ESLint does not recognize the types from `@vuelidate/core` when importing them

When working with TypeScript, the following import statement is valid: import { Validation, ValidatorFn } from '@vuelidate/core' However, this code triggers an error in ESLint: The message "ValidatorFn not found in '@vuelidate/core' ...

Distinguishing div identifiers for jQuery displaying and concealing

Although I am not a coder, I am still learning and trying to improve my skills. I have multiple div elements listed by a MySQL query. I require a JavaScript code that can display the class="qform" div based on which button is clicked. If button-1 is clic ...