Can't content dynamically added with v-html in vue be parsed by vue?

related answers

I haven"t been on codeshelper for too long. I only saw a friend asking for a specific solution under the question these two days when I logged in. I"m sorry I didn"t continue to follow this question and answer in time.

the reason why v-html cannot be parsed and compiled is also explained by the students who provide answers below. Here is a simple way to solve this problem with components:

// html
<div id="components-demo">

  <test-component :str="str"></test-component>

</div>
// js
Vue.component("test-component", {

  data: function () {

    return {

      inner_html: "this is a test!"

    }

  },

  template: `

    <div>

      <span v-html="inner_html"></span>

      <span>{{str}}</span>

    </div>

  `,

  props: ["str"]

})

new Vue({

  el: "-sharpcomponents-demo",

  data: {

    str: ""

  }

})

topic description

I used v-html to dynamically insert new HTML content with vue data binding content in a page. But it is not parsed. It shows {{title}}

related code

/ / Please paste the code text below (do not replace the code with pictures)

< html lang= "en" >
< head >

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="./js/jquery.min.js" type="text/javascript"></script>
<script src="js/vue.min.js"></script>


< body >

<div id="app">
    <div v-html="inner_html"></div>
</div>

<script>
    var vm = new Vue({
        el: "-sharpapp",
        data: {
            title: ""
        },
        methods: {

        },
        mounted: function() {
            this.inner_html = `
                    <div>{{title}}</div>
                `
        },
    });
</script>

< / body >
< / html >

question
but the page renders the background of the {{title}}

problem and what methods you have tried

tried to force re-rendering this.$forceUpdate ()-- but failed

related code

< script >

var vm = new Vue({
    el: "-sharpapp",
    data: {
        title: ""
    },
    methods: {

    },
    mounted: function() {
        this.inner_html = `
                <div>{{title}}</div>
            `
            
        this.$forceUpdate()
    },
});

< / script >

< H1 > ask for help < / H1 >
May.27,2021

updates the innerHTML of the element. Note: the content is inserted as normal HTML-it will not be compiled as a Vue template. If you try to use v-html composite templates, you can reconsider whether to use components instead.

v-html

vue the dependency collection is triggered by the html template, and then the get/set in data is updated and rendered, so it is impossible for you to listen for data changes through v-html . The document also says that you can use components instead.


take a look at what it says in the document

clipboard.png

Menu