I'm making some web features. But I have one problem. I wanted to create several html structures that added vue directives with v-html, but I couldn't. So, How can I render vue directives with v-html?
Of course I know this can cause xss vulnerability, but I will filter any critical tags so I don't care.
please share your tips!!
I already use Vue.compile function. But, it supports only full build and this don't match with my case.
<button @click="go()">go</button>
this is what i want to make using v-html. But @click directive is not rendered...
this is App.vue
result
But go button couldn't call go function.
App.vue
<template>
<div id="app">
<input type="text" v-model="name" />
<p v-html="name"></p>
<!-- Below tag is what i want to make using v-html -->
<!-- <button @click="go()">gogo</button> -->
</div>
</template>
<script>
// import HelloWorld from './components/HelloWorld.vue'
export default {
name: 'app',
data:function(){
return {
name:'',
}
},
methods:{
go(){
alert('hi');
}
}
}
</script>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
What you try to achieve is to compile a string as a Vue.js template component. You can use the ':is' directive to refer a dynamic component, and bind your local stringified data and functions from this dynamic component to your main Vue instance or component.
ie:
<div id="app">
<div :is="dynamicComponent"></div>
</div>
new Vue({
el: "#app",
data: {
template: '<button @click="sharedFun()">{{ sharedValue }}</button>',
sharedValue: 'this is a shared value'
},
computed: {
dynamicComponent() {
let f_sharedFunWithContext = typeof this.sharedFunWithContext === 'function'
? this.sharedFunWithContext
: () => {}
return {
template: this.template,
// redirect every shared data here
data: () => {
return {
sharedValue: this.sharedValue
}
},
// redirect every shared methods here
methods: {
sharedFun: () => {
return this.sharedFun()
},
sharedFunWithContext(params) {
// 'this' contains dynamic component context
return f_sharedFunWithContext(params);
}
}
}
}
},
methods: {
sharedFun() {
alert('do some secure stuff on root instance')
},
sharedFunWithContext() {
alert('do some secure stuff on root instance')
}
}
})
JSFiddle implementation: https://jsfiddle.net/jexzywua/1/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.