Search code examples
javascripthtmlvue.jsinsertmustache

Use moustache inside moustache brackets in vue?


I’m pretty new to Vue.js and love it so far. There’s only one problem I have: How do I render a string AND things inside the string? For example:

//…
data:{
string:"hi, {{name}}",
name:"John Doe"
}

{{string}}<!—won’t work —>
<span v-html="string"></span><!—neither this —>

I want to insert “string” into the html and afterwords insert “name”.

The “Hello {{name}}” should inserted after an Ajax call and therefore not be featured in the HTML.

The output should be “hi, John Doe”.

To make it clear, what I want to have is:

{{string}}
<!-- becomes-->
hi, {{name}}
<!--finally becomes-->
hi, John Doe


Solution

  • Use a computed property to return string with data variable inside string;

    <!DOCTYPE html>
    <html>
    <head>
      
    </head>
    <body>
      <div id="app">
        <h1>{{this.stringWithVar}}</h1>
      </div>
    
     <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
      <script>
        new Vue({
          el: '#app',
          data: {
          name: 'John Doe'
          },
          computed: {
            stringWithVar: function () {
              return `hi, ${this.name}`;
            }
           }
        })
      </script>
    </body>
    </html>