问题
I have an vue app and a global component. Both have a data property. For the component I use the x-template way to keep my html code together. I have encountered a strange error where the data was not available in the component, although the component was rendered properly when I didn't access the data in the component.
Here comes the HTML:
<h1>Hello</h1>
<div id='app'>
<p>Here is the app: {{message}}</p>
<my-component></my-component>
<script type="text/x-template" id="template">
<div>
<p>This is the component: {{secondmsg}}</p>
</div>
</script>
</div>
Here comes the .ts-file:
Vue.component('my-component',
{
template: '#template',
data: function () {
return {
secondmsg: 'Works again!'
}
}
});
var vm = new Vue({
el: '#app',
data: {
message: "App works!"
}
});
This does not work, it says
secondmsg is not defined
However, it works if you
- don't access secondmsg. Then, the component renders right. Or:
- if you don't use the x-template version but rather use inline-template for the component. Or:
- if you move the script section below the div closing the vue app
So after trying a lot, I found these workarounds, but I would really like to know why it matters where you define your x-template if you use the data (or the props) property. I didn't find any hint in the docs.
Note: I use Razor Pages with partial views, that's why in the standard case the x-template got rendered within the div.
Here's a fiddle to play around if you don't believe me :-)
回答1:
The reason for this problem is the following:
- Vue tries to render
#app
- Vue gets the the template to render from html DOM
- Vue sees that there is a
message
reference, this works - Vue sees that there is a component reference to
my-component
, it adds it to the render stack - Vue sees a reference to
secondmsg
, and then fails
If it didn't fail it would now continue with rendering my-component
As you already discovered, the following works for the problem:
- don't access secondmsg. Then, the component renders right. Or:
- if you don't use the x-template version but rather use inline-template for the component. Or:
- if you move the script section below the div closing the vue app
回答2:
The parent Vue is being attached to #app
, which includes the x-template. Attaching a Vue to an element tells Vue to use the contents of that element as a template to create the DOM. Since the x-template is in there, and it has an interpolation string in it, the parent Vue tries to do the interpolation, but secondmsg
isn't defined in the parent.
来源:https://stackoverflow.com/questions/49193378/why-does-position-of-x-template-section-matter-for-vue-templates-to-work-with-da