1👍
Uses Vue.component
to assembly JSON as one component may be one solution.
But you may need to adjust the HTML template in JSON. Because for supporting some features such as onclick
, binding class
, it will be one serious headache.
Below is one demo which may provide you some ideas how to reach your goal.
new Vue ({
el:'#app',
data () {
return {
"elements":[
{
"element":"dyno-text",
"value":"This fun here.<br> <button type='button' @click='changeTheme(this)' data-theme='sketchy' class='theme-link btn btn-light'>Sketchy</button>",
"class": 'text-success',
"methods": {
// changed onclick to @click, if you still like to use 'onclick' in the template, you have to define window.changeTheme
changeTheme: function(obj) {console.log('clicked')}
}
}
]
}
},
methods: {
createComponent(element) {
/*window.changeTheme = function () {
console.log('clicked by onclick')
}*/
return Vue.component(element.element, {
template: `<div ref="test">${element.value}</div>`,
mounted: function () {
this.$nextTick(() => {
this.$refs.test.querySelector('button.btn').classList.add(element.class)
// or adjust your template in JSON like `<button :class="classes"/>`, then binds element.class to data property=classes
})
},
methods: element.methods
})
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div id="app">
<div class="container">
<div v-for="(item, index) in elements" :key="index">
<component :is="createComponent(item)"/>
</div>
</div>
</div>
- [Vuejs]-Vue.js wont show more than one component on screen
- [Vuejs]-Property does not exist in this type
0👍
You can do something like this; I changed the element in order to create a known htmlElement, so what you do here is to iterate your array of elements and you insert them inside the body, set the value, and toggle the class.
–Edit–
Cleanner solution thanks to pointing it out supercool
let elements=[
{
"element":"div",
"value":"This fun here.<br> <button type='button' onclick='changeTheme(this)' data-theme='sketchy' class='theme-link btn btn-light'>Sketchy</button>",
"class": 'text-success'
}
]
elements.forEach((elemen,i)=>{
let createdElement= document.createElement(elemen.element)
createdElement.innerHTML = elemen.value
createdElement.classList.toggle(elemen.class)
document.body.appendChild(createdElement)
})
- [Vuejs]-Create Vue.js + Chart.js charts using datasets stored outside in a csv file
- [Vuejs]-Allow only one radio button to be true (get value from each item.value)
Source:stackexchange.com