JavaScript
x
36
36
1
const CustomComponent = {
2
props: ['index'],
3
template: `<span>I am a custom component: {{ index }}</span>`
4
};
5
6
const UserInputResult = {
7
components: {
8
CustomComponent
9
},
10
props: ['templateString'],
11
template: `<section v-html="templateString"></section>`
12
}
13
14
const app = new Vue({
15
el: '#app',
16
data(){
17
return {
18
userInput: 'user input example [:component-1]'
19
}
20
},
21
components: {
22
UserInputResult
23
},
24
methods: {
25
generateTemplate(){
26
let raw = this.userInput;
27
if (!!raw && raw.match(/[:component-d+]/g)) {
28
let components = [raw.match(/[:component-d+]/g)];
29
components.forEach(component => {
30
raw = raw.replace(component, `<custom-component :index="${component.match(/d+/)[0]}"></custom-component>`);
31
});
32
}
33
return raw;
34
}
35
}
36
})
JavaScript
1
5
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
2
<div id="app">
3
<textarea v-model="userInput"></textarea>
4
<user-input-result :template-string="generateTemplate()">
5
</div>
I want to render a custom component which has a dynamical template base on user input.
when user input a specific string ([:component-1]
), it will be render as a component (CustomComponent
)
how to achieve this?
Thanks a lot for anyone help!
Advertisement
Answer
I figured it out by using Vue.complie
according to dynamically-fetch-and-compile-a-template-with-nuxt
JavaScript
1
12
12
1
const UserInputResult = {
2
props: ['templateString'],
3
render(h){
4
return h({
5
components: {
6
CustomComponent
7
},
8
template: `<section>${this.templateString}</section>`
9
});
10
}
11
}
12