【问题标题】:Dynamic vue.js components that aren't in the parent不在父级中的动态 vue.js 组件
【发布时间】:2015-11-13 09:52:39
【问题描述】:

我想将 Vue 的动态组件 (http://vuejs.org/guide/components.html#Dynamic_Components) 用于在子对象而不是父对象中定义的组件。例如:

new Vue({
  el: 'body',
  components: {
    'post': require('./post')
});

// post.js

module.exports = {
  inherit: true,

  data: function () {
      return {
          currentView: 'create-post'
      }
  },
  components: {
     'create-post': require('./create-post'),
     'update-post': require('./update-post')
  }
}

<component is="{{ post.currentView }}"></component>

或者更好

<post is="{{ currentView }}"></post>

据我所知,由于父母是唯一可以访问<component> 标签的人,因此不可能使用第二级孩子。是我对结构的思考不正确,还是有办法完成上述操作?

【问题讨论】:

    标签: vue.js


    【解决方案1】:

    所以,实习生帮我解决了这个问题……呃,尴尬。

    我上面的问题只是范围,这些最佳实践描述了修复它的弓:http://vuejs.org/guide/best-practices.html#Component_Scope

    本质上,我只需要一个额外的视图层组件来让“post”拥有适当的子范围。显示比描述容易:

    new Vue({
      el: 'body',
      components: {
        'post': require('./post')
    });
    
    // post.js
    module.exports = {
      inherit: true,
    
      template: document.querySelector('#post'),
    
      data: function () {
          return {
              currentView: 'create-post'
          }
      },
      components: {
         'create-post': require('./create-post'),
         'update-post': require('./update-post')
      }
    }
    
    // create-post.js
    module.exports = {
      inherit: true,
      template: document.querySelector('#create-post'),
    }
    
    // update-post.js
    module.exports = {
      inherit: true,
      template: document.querySelector('#update-post'),
    }
    
    // main.html
    <html>
      <body>
        <post></post>
      </body>
    </html>
    
    // post.html
    <script id="post" type="x-template">
      <component is="%% currentView %%"></component>
    </script>
    
    // create-post.html
    <script id="create-post" type="x-template">
      <h1>Create a post</h1>
    </script>
    
    // update-post.html
    <script id="create-post" type="x-template">
      <h1>Update a post</h1>
    </script>
    

    【讨论】:

    • "...实习生" 呵呵。感谢您的回答足够大,可以将他们归功于他们。不知道是生活中的事实,没有什么可耻的。我们都对某事了解一点,而对其他所有事情了解的不多。 ;-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-07
    • 1970-01-01
    • 2021-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-13
    相关资源
    最近更新 更多