【发布时间】:2018-08-18 00:03:56
【问题描述】:
我有一个 vue 应用和一个全局组件。两者都有数据属性。对于组件,我使用 x-template 方式将我的 html 代码放在一起。我遇到了一个奇怪的错误,即组件中的数据不可用,尽管当我没有访问组件中的数据时组件已正确呈现。
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>
.ts 文件来了:
Vue.component('my-component',
{
template: '#template',
data: function () {
return {
secondmsg: 'Works again!'
}
}
});
var vm = new Vue({
el: '#app',
data: {
message: "App works!"
}
});
这不起作用,它说
secondmsg 未定义
但是,如果你这样做,它会起作用
- 不要访问 secondmsg。然后,组件呈现正确。或者:
- 如果您不使用x-template 版本,而是使用inline-template 作为组件。或者:
- 如果将脚本部分移到 div 下方,关闭 vue 应用程序
所以在尝试了很多之后,我找到了这些解决方法,但我真的很想知道如果你使用 data (或 props )属性,在哪里定义你的 x-template 很重要。我在文档中没有找到任何提示。
注意:我使用带有部分视图的 Razor 页面,这就是为什么在标准情况下 x 模板在 div 中呈现。
Here's a fiddle 如果你不相信我就去玩 :-)
【问题讨论】:
标签: vue.js vue-component