slot插槽

slot 插槽:用于组件之间传值。

需求:在 components 文件夹下创建 myslot 组件,然后在 HelloWorld 组件中引用 myslot 组件,把 HelloWorld 组件中的数据传递给 myslot 组件。

先使用传统的方式,即父组件向子组件传值,代码如下。

(1)HelloWorld 组件代码如下。

<template>
  <div class="hello">
    //3.引用组件并使用属性绑定的形式,把父组件数据传递给子组件
    <myslot :sendMsg="msg"></myslot>
  </div>
</template>

<script>
//1.在HelloWorld组件中引入myslot组件
import myslot from './myslot'

export default {
  name: "HelloWorld",
  data() {
    return {
      msg: 'Welcome to Your Vue.js App'
    };
  },
  components: {
    //2.在components属性注册myslot组件
    myslot
  }
};
</script>

<style scoped>
.active {
  background: red;
}
</style>

(2)myslot组件代码如下。

<template>
  <div>
    <h1>slot的使用</h1>
    <h1>传统方式:{{ sendMsg }}</h1>
  </div>
</template>

<script>
export default {
  props: ['sendMsg']
};
</script>

<style scoped>

</style>

上述代码为使用传统方式传值,下面使用 slot 插槽形式进行父子组件传值,代码如下。

(1)HelloWorld组件代码如下。

<template>
  <div class="hello">
    <myslot>
      //1.把msg数据使用插值表达式形式,放到myslot标签中
      {{ msg }}
    </myslot>
  </div>
</template>

(2)myslot组件代码如下。

<template>
  <div>
    <h1>slot插槽方式</h1>
    <h1><slot></slot></h1>
  </div>
</template>

代码解析如下。

  • 使用 slot 插槽,只需要在引用组件时,把要传递的数据使用插值表达式的形式,放到组件标签中。

  • 在子组件中使用 <slot></slot> 标签接收数据。

具名插槽(多数据传递):使用上述方法,不管传递了多少数据,都会在 h1 标签中显示,下面的方法可以让传递的数据在不用标签的情况下显示,代码如下。

HelloWorld组件视图层

<template>
  <div class="hello">
    <myslot>
      <div slot="msg1">{{ msg }}</div>
      <div slot="msg2">{{ num }}</div>
    </myslot>
  </div>
</template>

myslot组件视图层

<template>
  <div>
    <h1>slot插槽方式</h1>
    <h1><slot name="msg1"></slot></h1>
    <h2><slot name="msg2"></slot></h2>
  </div>
</template>

代码解析如下。

在子组件接收时给 slot 添加 name 属性,name 的属性值就是父组件中元素的 slot 属性值。