Shankar Thiyagaraajan Shankar Thiyagaraajan - 6 days ago 6
HTML Question

Dynamic Template (Component) Probs to Class Binding Issue using Vue Js

I try to make dynamic template to assign the class by condition base.

My Template is :

<template v-if="showTemplate" id="campaignBlock">
<div v-class="@{{ block_class }}">
// <div v-class="{ block_class }">
<img src="{{URL::asset('uploads/default.png')}}">
</div>




Template Call :

<input type="button" @click="nb += 1" class="btn btn-default" value="Add New Section">
<div v-for="a in nb">
<block v-if="nb == 4" block_class="col-md-3 col-sm-6 col-xs-6"></block>
<block v-if="nb == 3" block_class="col-md-4 col-sm-6 col-xs-6"></block>
<block v-if="nb == 2" block_class="col-md-6 col-sm-6 col-xs-6"></block>
<block v-if="nb == 1" block_class="col-md-12 col-sm-6 col-xs-6"></block>
</div>


VueJs :

Vue.component('block', {
template: '#campaignBlock',
props: ['block_class'],
data: function () {
return {
n: 0,
nb: 1,
block_class: 'col-md-3 col-sm-6 col-xs-6'
}
}
});


Here, if I increase the columns, then I get expected props value in template as a variable.

ex.
<div v-class="{{ block_class }}">


But, if I try to assign in a "class", just present as text. Also I tried native class too. I can't pass the pros(block_class) to the template.

Any possible way to handle this issue? I'm using Laravel.

Answer

You can use dynamic styling for doing this,

You may pass a object hash in props to the component like following:

<input type="button" @click="nb += 1" class="btn btn-default" value="Add New Section">
<div v-for="a in nb">
   <block v-if="nb == 4" block_class="{'col-md-3': true, 'col-sm-6': true, 'col-xs-6': true"></block>
</div>

and in the template code:

<template v-if="showTemplate" id="campaignBlock">
   <div :class="block_class">
// <div :class="block_class">
     <img src="{{URL::asset('uploads/default.png')}}">
  </div>
Comments