【问题标题】:Is it possible put in directives in v-html directive?是否可以在 v-html 指令中放入指令?
【发布时间】:2020-01-06 22:31:19
【问题描述】:

我正在制作一些网络功能。但我有一个问题。 我想创建几个使用 v-html 添加 vue 指令的 html 结构,但我做不到。 那么,如何使用 v-html 渲染 vue 指令?

当然我知道这会导致 xss 漏洞,但我会过滤任何关键标签,所以我不在乎。

请分享您的建议!

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

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

这是App.vue结果

但是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 语法部分?
  • 试试v-on 类似v-on="{click: go()}"
  • @skirtle 我想使用更多指令,而不仅仅是v-on v-html 中的事件监听器 :)
  • @Michael 感谢您分享提示!但是&lt;button v-on="{click: go()}"&gt;go&lt;/button&gt; 也没有工作:,(
  • 如果我理解的话,你会将动态 Vue 模板 '' 放在名称 var 中,然后渲染它?

标签: javascript html vue.js vuejs2


【解决方案1】:

您尝试实现的是将字符串编译为 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/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-10
    • 2020-11-09
    • 2015-10-29
    • 2020-05-25
    • 2018-04-28
    • 1970-01-01
    • 2017-01-06
    • 1970-01-01
    相关资源
    最近更新 更多