繁体   English   中英

是否可以在v-html指令中放入指令?

[英]Is it possible put in directives in v-html directive?

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

当然,我知道这可能导致xss漏洞,但是我将过滤所有关键标签,所以我不在乎。

请分享您的提示!!

  1. 我已经使用了Vue.compile函数。 但是,它仅支持完整版本,而这与我的情况不符。

  2. <button @click="go()">go</button>这是我想使用v-html制作的。 但是不会呈现@click指令...

这是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>

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM