Render and Compile String using vue.js

纵然是瞬间 提交于 2019-12-08 08:05:55

问题


There is a requirement where all html elements are defined in a JSON file and used in the template.

There is a function - "markComplete" which needs to be triggered on change of a checkbox.

Code Template:

<template>
<span v-html="htmlContent"></span>
</template>

<script>
 data(){
        return{
        htmlContent: "<input type='checkbox' v-on:change='markComplete'>"
        }
    }
</script>

Above code won't work as onChange event won't be mounted, and I get Uncaught ReferenceError: markComplete is not defined

Is there any way to make this work?


回答1:


You are trying to compile the string as Vue Templates using v-html.

Note that the contents are inserted as plain HTML - they will not be compiled as Vue templates

Read about v-html in Vue Docs.

As solution you can read this article

You don't want to use a library? Checkout the code below:

First create a js file (preferably RenderString.js):

import Vue from "vue"

Vue.component("RenderString", {
  props: {
    string: {
      required: true,
      type: String
    }
  },
  render(h) {
    const render = {
      template: "<div>" + this.string + "</div>",
      methods: {
        markComplete() {
          console.log('the method called')
        }
      }
    }
    return h(render)
  }
})

Then in your parent component:

<template>
  <div><RenderString :string="htmlContent" /></div>
</template>

<script>
import RenderString from "./components/RenderString"

export default {
  name: "App",
  data: () => ({
    htmlContent: "<input type='checkbox' v-on:change='markComplete'>"
  })
}
</script>

Note: I didn't run the code above but I created a similar working CodeSandbox Example



来源:https://stackoverflow.com/questions/54617255/render-and-compile-string-using-vue-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!