Skip to content
Advertisement

How to clean up v-bind directives from html code in Vue?

Ok, I’ve got some Vue code and HTML.

For 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']
});

And in my page:

<div is="area-selectors-box" v-bind:selects="selects"></div>

It all works, but if I read the page source, I see the v-bind:selects="selects" portion, which is not standard compliant, I guess.

Similarly, other components have other object properties like:

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

which on the page source evaluates to something like:

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

which is obviously not desirable.

How do I bind these properties without them appearing in the DOM as attributes?

Advertisement

Answer

My own answer is: pass props when you call the component, not in the component itself. This code will work and produce clean html:

In-page HTML:

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

JS:

Vue.component('area-selectors-box', { // pass 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', { // pass area to area-option
  template: `
    <select @change="selected" >
      <option disabled selected value="">Seleziona continente</option>
      <area-option v-for="area in select.areas" :area="area" :key="area.term_id"></area-option>
    </select>
  `
  ,props:['select']
});

Vue.component('area-option', { // pass nothing
  template: `<option :value="area.term_id">{{area.name}}<slot></slot></option>`
  ,props: ['area']
});
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement