2015-07-10 95 views
14

这可能听起来像一个真正的noob问题,但我很新MVVM ...甚至在JS的MVC,所以提前抱歉。嵌套vue.js实例/元素

我在玩vue.js,并且非常喜欢它的简单性。但是对于我想要做的事情,我想我需要以不同的方式去做。

我想将Vue实例/元素嵌套在彼此的内部,但当然,当它在init上读取DOM时,父级会使用子级。

对于参数的缘故,下面是我的意思,我没有做这样的事的例子,但这是列举了最简单的方法是什么我的意思是:

<body> 
    {{ message }} 
    <div id="another"> 
     {{ message }} 
    </div> 
</body> 

然后我JS的例子是:

new Vue({ 
    el: "body", 
    data: { 
     message: "I'm the parent" 
    } 
}); 

new Vue({ 
    el: "#another", 
    data: { 
     message: "I'm the child" 
    } 
}); 

的结果将是:

<body> 
    I'm the parent 
    <div id="another"> 
     I'm the parent 
    </div> 
</body> 

现在我完全易懂nd为什么这样做,事实上,它应该这样做,但我的例子只是试图说明我会如何做这样的事情?

在我现实生活中的项目中,当身体发生某些事情(在许多地方)时,我的身体上会有一个v级的变化,但当然我的身体也会需要其他vue实例来做其他事情。

我将如何去嵌套?是否有功能来处理这个问题?我需要处理组件吗?或者,也许,从一个子元素(例如像jQuery将与$(“身体”)),然后在Vue实例内操纵它的内部获取身体?

希望这个问题不是太愚蠢,有人可以指向正确的方向。

谢谢

回答

3

通过道具传递数据只是一种方法。嵌套组件并从父项继承工作良好。

例子:http://jsfiddle.net/hajkrupo/3/

<encapsulated-component inline-template> 
    <header> 
     <cart-status></cart-status> 
    </header> 
    <cart></cart> 
</encapsulated-component> 
0

你可以用<slot>标签做到这一点。这是一个例子。

1.因此,首先,您需要做的是创建一个基本的布局组件,就像这样。 你需要添加<slot>无论你想要的标签。非常重要的一点是,名称属性上的<slot>标签。

var basicLayout = Vue.component("basic-layout", { 
    template: ` 

    <div class="basic-layout"> 
     <header> 
      <slot name="header"></slot> 
     </header> 
     <main> 
      <slot></slot> 
     </main> 
     <footer> 
      <slot name="footer"></slot> 
     </footer> 
    </div> 

    ` 
}); 

2.然后创建您的自定义组件。我创建了myHeader组件向您展示,它是如何工作的。

var myHeader = Vue.component("my-header", { 
    template: ` 

    <div class="header"> 
     <ul> 
      <li>HOME</li> 
      <li>ABOUT</li> 
      <li>CONTACT</li> 
     </ul> 
    </div> 

    ` 
}); 

3.将此示例代码放入HTML文件中。 要在当前插槽中放置一些内容,只需在组件或标签中使用slot属性即可。

<div class="app"> 
    <basic-layout> 
     <my-header slot="header"></my-header> 

     <p>Content in &lt;main&gt; tag</p> 

     <p slot="footer">Content in footer</p> 
    </basic-layout> 
</div> 

4,结果会是这样的:

<div class="app"> 
    <div class="basic-layout"> 
     <header> 
      <div class="header"> 
       <ul> 
       <li>HOME</li> 
       <li>ABOUT</li> 
       <li>CONTACT</li> 
       </ul> 
      </div> 
     </header> 

     <main> 
     <p>Content in &lt;main&gt; tag</p> 
     <main> 

     <footer> 
      <p>Content in footer</p> 
     </footer> 
    </div> 
</div> 

请参阅Vue.js 的官方页面的文档只需要点击链接here获取更多信息。

这里是jsfiddle的示例