Reputation: 53
I am in the process of learning Vue. As far as I know I should be able to use a simple template string as a template in Vue. But for some reason, Vue renders only the first html tag.
Vue.config.devtools = true;
let template = `<h2>Hi {{name}}</h2><h1>{{age}}</h1>`
const vm = new Vue({
el: '#app',
data() {
return {
name: 'Name',
age: 23,
message: 'hello'
}
},
template,
methods: {
greet(e) {
return this.message = e.target.value
},
esc(e) {
e.target.value = ''
}
}
})
<div id="app"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
This renders only "Hi Name". Why isn't age showing up?
Upvotes: 4
Views: 20007
Reputation: 161
After search a lot ways to implement component template even this one - all searchers need to know it must chance this flag to true - and add 10Kb to final result hahaha - this little one will add the compiler to properly do work - by default its false
// if you are using VUE -> vue.config.js module.exports = { runtimeCompiler: true };
// if you are using VUE+QUASAR -> quasar.config.js add at -> build: { vueCompiler: true, }
Upvotes: 1
Reputation: 1073968
A couple of issues:
As Sergeon said, there must be one root node, not two.
Vue's templates are different from JavaScript's template literals. You've used Vue's syntax ({{name}}
), but in a JavaScript template literal. You probably wanted a simple string. (Although you could certainly use an untagged template literal instead if you wanted, since they evaluate to strings. Just not that {{name}}
and such placeholders are handled by Vue, and ${name}
and such will be handled by the JavaScript template itself.)
Fixing those, it seems to work:
Vue.config.devtools = true;
let template = "<div><h2>Hi {{name}}</h2><h1>{{age}}</h1></div>";
const vm = new Vue({
el: '#app',
data() {
return {
name: 'Name',
age: 23,
message: 'hello'
}
},
template,
methods: {
greet(e) {
return this.message = e.target.value
},
esc(e) {
e.target.value = ''
}
}
})
<div id="app"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
Upvotes: 0
Reputation: 6788
Vue templates should have only one root node. I think you should have a message in your console warning about that.
Try:
let template = `<div><h2>Hi {{name}}</h2><h1>{{age}}</h1></div>`
Upvotes: 3