简体   繁体   English

无法将属性传递给vue.js中插槽中的组件?

[英]Cannot pass properties to a component in a slot in vue.js?

I'm trying to use Vue.js (v2.1.3) to create nested components but I can't figure out how to bind data between them. 我正在尝试使用Vue.js(v2.1.3)来创建嵌套组件,但我无法弄清楚如何在它们之间绑定数据。

This JSFiddle demonstrates what I'm trying to achieve. 这个JSFiddle演示了我想要实现的目标。

HTML... HTML ...

 <div id="test">
   <comp1>
     <comp2 :message="message"></comp2>
   </comp1>
 </div>

JS... JS ...

    var template = `<div>
      <comp2 :message="message"></comp2>
      <slot :message="message"></slot>
    </div>`;

    Vue.component("comp1", {
      template: template,
      data: function() {
        return {
          message: "Hello"
        };
      }
    });

    var template2 = `<div>
       <span>Message is: {{ message }}</span>
    </div>`;

    Vue.component("comp2", {
      template: template2,
      props: ["message"]
    });

    new Vue({
      el: "#test"
    });

If I declare the child component directly in the template of the parent component then the data is passed correctly. 如果我直接在父组件的模板中声明子组件,则正确传递数据。 But when the child component is assigned to a slot in the parent component then the data is not passed. 但是,当子组件分配给父组件中的插槽时,则不传递数据。

I've read and re-read the documentation but can't figure out whether what I want to do is possible and if so, what it is that I'm doing wrong. 我已阅读并重新阅读文档,但无法弄清楚我想做的事情是否可行,如果可能,我做错了什么。

Any help resolving this would be greatly appreciated! 任何帮助解决这个问题将不胜感激!

To use scoped slots, wrap your parent's content in a template tag with a scope attribute: 要使用作用域插槽,请将父级内容包含在带有scope属性的template标记中:

<comp1>
  <template scope="{ message }">
    <comp2 :message="message"></comp2>
  </template>    
</comp1>

Here's your updated fiddle: https://jsfiddle.net/Lbz6Ly4a/1/ 这是你更新的小提琴: https//jsfiddle.net/Lbz6Ly4a/1/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM