Home > OS >  How to handle event on html render by computed function in vue js?
How to handle event on html render by computed function in vue js?

Time:07-22

I'm using vue 2. I have a text get from api.

"Hello everyone! My name is [input]. I'm [input] year old".

Now, I have to replace the [input] with an html input and handle the onKeyUp for this input.

What I have to do?

I used computed render html, but it not work with v-on:xxx.

content.replaceAll('[answer]', '<input type="text"  v-on:click="handleInput()"/>')

Thanks!

CodePudding user response:

After spending an hour and so on this requirement, I came up with the solution.

Here you go (I added all the descriptive comments/steps in the below code snippet itself) :

// Template coming from API
var textFromAPI = "<p>Hello everyone! My name is [input]. I'm [input] year old</p>";

// getting the array of input tags. So that we can loop and create the proper input element.
const matched = textFromAPI.match(/(input)/g);

// Iterating over an array of matched substrings and creating a HTML element along with the required attributes and events.
matched.forEach((el, index) => {
    textFromAPI = textFromAPI.replace('[input]', `<input type="text" id="${index   1}" v-model="inputValue[${index}]" v-on:keyup="getValue"/>`);
})

// Here, we are compiling the whole string so that it will behave in a Vue way.
var res = Vue.compile(textFromAPI)

var app = new Vue({
  el: '#app',
  data: {
    compiled: null,
    inputValue: []
  },
  render: res.render,
  staticRenderFns: res.staticRenderFns,
  mounted() {
    setTimeout(() => {
      this.compiled = res;
    })
  },
  methods: {
    getValue() {
      // Here you will get the updated values of the inputs.
      console.log(this.inputValue);
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
</div>

CodePudding user response:

Thanks @ Rohit Jíndal, but! When I use vue2 and it doesn't work. And there is an error:

TypeError: Cannot read properties of undefined (reading 'string')

I build this to a component and use anywhere in my project.

<render-html :text="question.quest_content" @handleAnswer="handleAnswer"></render-html>

enter image description here

CodePudding user response:

I used and it's work.

this.$options.staticRenderFns = string.staticRenderFns;
return string.render.bind(this)(h)

Thanks so much!

  • Related