[Vuejs]-VueJs, Template, v-bind, embeded html

0πŸ‘

βœ…

I was running a test, and came back to see the added comment about removing the <template> tag, which I agree with.

However, you also have a problem in that you are trying to bind myName to a <div> tag name attribute, which doesn’t exist. Use handle bars instead.

Here is the working code:

<!DOCTYPE html>
<html lang="en">

<head>
  <title>Template and v-bind</title>
</head>

<body>
  <!-- Div to Mount App -->
  <div id="app"></div>

  <!-- Reference to Vue.js library -->
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

  <!-- Script Element for our App -->
  <script>
    var app = new Vue({
      el: '#app',
      data: {
        myName: 'Cool Name'
      },
      template: `
                <div>
                    <div>{{ myName }}</div> 
                </div>`

    });
  </script>

</body>

</html>

0πŸ‘

You can render property value as html content but it will be rendered literally at html content not effected by VueJS
So in the following code

<html lang="en">
    <head>
        <title>Template and v-bind</title>
    </head>
    <body>
        <!-- Div to Mount App -->   
        <div id="app" v-html="htmlCont">{{ htmlCont }}</div>
        <!-- Reference to Vue.js library -->
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
        <!-- Script Element for our App -->
        <script>
            var app = new Vue({
                el: '#app',
                data: {
                    myName: 'Cool Name',
                    htmlCont: `
                    <div>
                        <div>{{ myName }}</div> 
                    </div>`
                },   
            });
        </script>
    </body>
</html>

I successfully placed this html inside

<div>
    <div>{{ myName }}</div> 
</div>

But (myName) variable will not be rendered by VueJS
So you have to use Vue Component instead as follow

<html lang="en">
    <head>
        <title>Template and v-bind</title>
    </head>
    <body>
        <!-- Div to Mount App -->   
        <div id="app"><html-cont></html-cont></div>
        <!-- Reference to Vue.js library -->
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
        <!-- Script Element for our App -->
        <script>
            data_obj = {
                myName: 'Cool Name'
            }
            Vue.component('html-cont',{
                data: function() { return data_obj},
                template: `
                    <div>
                        <div>{{ myName }}</div> 
                    </div>`
                }
            );
            var app = new Vue({
                el: '#app',
                data: data_obj
            });
        </script>
    </body>
</html>

Leave a comment