简体   繁体   English

vue.js 和属性中的插槽

[英]vue.js and slot in attribute

I'm trying to build a vue.js template that implements following:我正在尝试构建一个实现以下功能的 vue.js 模板:

  • <MyComponent></MyComponent> generates <div class="a"></div> <MyComponent></MyComponent>生成<div class="a"></div>
  • <MyComponent>b</MyComponent> generates <div class="a" data-text="b"></div> . <MyComponent>b</MyComponent>生成<div class="a" data-text="b"></div>

Is such a thing possible?这样的事情可能吗?

EDIT编辑

Here is the best I can reach:这是我能达到的最好的:

  props: {
    text: {
      type: [Boolean, String],
      default: false
    }
  },

and template和模板

<template>
  <div :class="classes()" :data-text="text">
    <slot v-bind:text="text"></slot>
  </div>
</template>

but the binding does not work, text always contains false .但绑定不起作用, text始终包含false

You're mixing slots and properties here.您在这里混合插槽和属性。 You'll have to pass whatever you want to end up as your data-text attribute as a prop to your component.您必须将任何您想要最终作为data-text作为道具传递给您的组件。

<MyComponent text="'b'"></MyComponent>

And in your template you can remove the slot在您的模板中,您可以删除插槽

<template>
    <div :class="classes()" :data-text="text"></div>
</template>

Another thing: it looks like your binding your classes via a method.另一件事:看起来你通过一个方法绑定你的类。 This could be done via computed properties, take a look if you're not familiar.这可以通过计算属性来完成,如果您不熟悉,请查看。

You can use the mounted() method to get text using $slot.default property of the component to get the enclosing text.您可以使用mounted()方法获取文本,使用组件的$slot.default属性来获取封闭文本。 Create a text field in data and update inside mounted() method like this:在数据中创建一个文本字段并在mounted()方法中更新,如下所示:

Vue.component('mycomponent', {
  data: () => ({
    text: ""
  }),
  template: '<div class="a" :data-text=text></div>',
  mounted(){
    let slot = this.$slots.default[0];
    this.text=slot.text;

  }
});

Note: It will only work for text, not for Html tags or components.注意:它仅适用于文本,不适用于 Html 标签或组件。

You can try this.你可以试试这个。

<template>
  <div :class="classes()">
    <slot name="body" v-bind:text="text" v-if="hasDefaultSlot">
    </slot>
  </div>
</template>


computed: {
    hasDefaultSlot() {
        console.log(this)
        return this.$scopedSlots.hasOwnProperty("body");
    },
}


Calling

<MyComponent>
<template v-slot:body="props">
b
</template>
</MyComponent>

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

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