一、插槽

  • 插槽,让父组件可以向子组件指定位置插入html结构,也是一种组件间通信的方式,适用于父子组件(父传子),可以用于组件的二次封装。
  • 插槽分类:默认插槽、具名插槽、作用域插槽

二、默认插槽

        当父组件没有插入时,插槽显示默认内容

//父组件
<template>
  <div class="home">
    <h1>我是父组件</h1>
    <HelloWorld msg="Welcome to Your Vue.js App">
      <h2>父组件插入元素</h2>
    </HelloWorld>
  </div>
</template>

<script>
// @ is an alias to /src
import HelloWorld from '@/components/HelloWorld.vue'

export default {
  name: 'Home',
  components: {
    HelloWorld
  }
}
</script>

//子组件
<template>
  <div>
    <h1>我是子组件</h1>
    <slot>我是插槽</slot>
  </div>
</template>

<script>
export default {

}
</script>

<style>

</style>

二、具名插槽

        实现父组件向子组件指定位置添加元素

//父组件
<template>
  <div class="home">
    <h1>我是父组件</h1>
    <HelloWorld msg="Welcome to Your Vue.js App">
      <h2 slot="name">我的名字叫做{{name}}</h2>
      <h2 slot="age">我的年纪{{age}}</h2>
    </HelloWorld>
  </div>
</template>

<script>
// @ is an alias to /src
import HelloWorld from '@/components/HelloWorld.vue'

export default {
  name: 'Home',
  components: {
    HelloWorld
  },
  data(){
    return {
      name:"张三",
      age:18
    }
  }
}
</script>

//子组件
<template>
  <div>
    <h1>我是子组件</h1>
    <slot name="name"></slot>
    <hr/>
    <slot name="age"></slot>
  </div>
</template>

<script>
export default {

}
</script>

<style>

</style>

三、作用域插槽

        数据在组件的自身,但根据数据生成的结构需要组件的使用者来决定,比如两个地方都需要使用这个子组件,但是在子组件需要展示不同是数据结构,可以通过这个方法解决。

//父组件根据子组件的数据生成对应的结构插入到子组件中去
<template>
  <div class="home">
    <h1>我是父组件</h1>
    <HelloWorld msg="Welcome to Your Vue.js App">
      <template scope="scopeData">
        <ul>
          <li v-for="g in scopeData.list">{{g}}</li>
        </ul>
      </template>
    </HelloWorld>
  </div>
</template>

<script>
// @ is an alias to /src
import HelloWorld from "@/components/HelloWorld.vue";

export default {
  name: "Home",
  components: {
    HelloWorld,
  },
};
</script>

//子组件将数据传递给父组件
<template>
  <div>
    <h1>我是子组件</h1>
    <slot :list="list"></slot>
  </div>
</template>

<script>
export default {
  name:"HelloWorld",
  data(){
    return{
      list:["面试","上班","摸鱼","混工资","躺平","重开"]
    }
  }
}
</script>

<style>

</style>

Logo

前往低代码交流专区

更多推荐