1

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?

2
  • The json file is just a string, cannot contain methods. makeComplete would have to be defined somewhere in the Vue app - where is it? Commented Feb 10, 2019 at 21:58
  • @RichardMatsen That is present in methods, i just didn't mention it Commented Feb 13, 2019 at 4:37

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

2 Comments

thanks for the edit. This works fine but function defined in parent component should be called. I tried to emit event on change - this.$emit('ParentFunction'); On doing this, there is neither error nor warning. Where am I going wrong? CodeSandbox - codesandbox.io/s/k34x9jk02r
Glad to read that it helped. Though I changed the sandbox using $emit. If you want you can take a look -> codesandbox.io/s/x2vry0m8mp

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.