【问题标题】:Why does position of x-template section matter for vue templates to work with data?为什么 x-template 部分的位置对于 vue 模板处理数据很重要?
【发布时间】: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


    【解决方案1】:

    出现这个问题的原因如下:

    1. Vue 尝试渲染 #app
    2. Vue 从 html DOM 获取要渲染的模板
    3. Vue 发现有一个 message 引用,这行得通
    4. Vue 发现有一个组件引用了my-component,它把它添加到渲染堆栈中
    5. Vue 看到对 secondmsg 的引用,然后失败

    如果它没有失败,它将继续渲染my-component

    正如您已经发现的那样,以下方法可以解决该问题:

    • 不要访问 secondmsg。然后,组件呈现正确。或者:
    • 如果您不使用 x-template 版本,而是使用 inline-template 作为组件。或者:
    • 如果将脚本部分移到 div 下方,关闭 vue 应用程序

    【讨论】:

      【解决方案2】:

      父 Vue 已附加到 #app,其中包括 x 模板。将 Vue 附加到元素告诉 Vue 使用该元素的内容作为模板来创建 DOM。由于 x-template 在那里,并且其中有一个插值字符串,父 Vue 尝试进行插值,但父 Vue 中没有定义 secondmsg

      【讨论】:

      • 非常感谢,非常感谢您的帮助!我标记@Ferrybig 答案的原因主要是他到目前为止的名声较低:-)
      猜你喜欢
      • 2020-11-27
      • 2015-09-07
      • 1970-01-01
      • 2014-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-19
      • 1970-01-01
      相关资源
      最近更新 更多