可以在v-html指令中添加指令吗?

4

我在制作一些网页功能,但是遇到了一个问题。
我想创建几个HTML结构并使用v-html添加Vue指令,但我无法实现。
那么,如何使用v-html渲染Vue指令呢?

当然,我知道这可能会导致XSS漏洞,但我会过滤任何关键标记,所以我不在意。

请分享你的技巧!

  1. 我已经使用Vue.compile函数,但它只支持完整的构建,这与我的情况不匹配。

  2. <button @click="go()">go</button> 这就是我想要使用v-html制作的内容。但是@click指令没有被渲染...

这是App.vue的结果:

Imgur

但是go按钮不能调用go函数。


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>


您只需要事件监听器还是在 v-html 中需要Vue语法的其他部分? - skirtle
尝试使用 v-on,类似于 v-on="{click: go()}" - Michael
@skirtle 我想在 v-html 中使用更多的指令,而不仅仅是 v-on 事件监听器 :) - leesh
1
@Michael 谢谢你分享的技巧!但是 <button v-on="{click: go()}">go</button> 也不起作用 :,( - leesh
@Sackey 正确!!非常感谢你!!! - leesh
显示剩余3条评论
1个回答

3
您想要实现的是将一个字符串编译为Vue.js模板组件。您可以使用“:is”指令来引用动态组件,并将该动态组件中序列化的数据和函数与主Vue实例或组件绑定。
例如:
<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实现:https://jsfiddle.net/jexzywua/1/

在Vue3中,我需要通过添加代码来进行即兴创作。 ``` - Olotin Temitope

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接