[Vuejs]-How to create a dynamic class value in a component in VueJS?

1πŸ‘

βœ…

It should be really simple hopefully. Not sure if syntax is correct as I am using webpack and single file components, so sorry if some issue with syntax.

One way:

Vue.component('m-textbox', {
  template: 
   `<div>
    <div :class="size">
      <input :id="id" type="text" :value="value" @input="$emit('input', $event.target.value)">
      <label :for="id">{{ label }}</label>
    </div>
   </div>`
  ,
  props: ["id", "value", "label", "for", 
           size: 
           { type: 'string', default: 'input-field col s12 m6 l6'}]
})

Other way:

Vue.component('m-textbox', {
  template: 
    `<div class="input-field">
      <input :id="id" type="text" :value="value" @input="$emit('input', $event.target.value)">
      <label :for="id">{{ label }}</label>
    </div>`
  ,
      props: ["id", "value", "label", "for"]
    })

and use it:
<m-textbox v-model="full_name" id="full_name" label="Full Name" v-bind:class="[col, s12, m6]"></m-textbox>

1πŸ‘

You could remove the outer div in your component template and simply add the class attribute to your component. It will even merge your classes.

Vue.component('m-textbox', {
  template: `
    <div class="input-field col">
      <input :id="id" type="text" :value="value" @input="$emit('input', $event.target.value)">
      <label :for="id">{{ label }}</label>
    </div>
  `,
  props: ["id", "value", "label", "for"]
})

<m-textbox v-model="full_name" id="full_name" label="Full Name" class="s12 m6 l6"></m-textbox>
πŸ‘€smek

Leave a comment