当前位置: 移动技术网 > IT编程>脚本编程>vue.js > Vue-slot插槽的所有使用方法

Vue-slot插槽的所有使用方法

2020年07月24日  | 移动技术网IT编程  | 我要评论

1.插槽的基本使用

<div id="app">
  <cpn><button>按钮</button></cpn>
</div>

//定义一个组件
<template id="cpn">
  <div>
    <h2>我是组件</h2>
    <p>我是内容</p>
    <slot></slot>
  </div>
</template>
const vm = new Vue({
  el: '#app',
  //注册组件
  components: {
    cpn: {
      template: '#cpn'
    }
  }

});

在这里插入图片描述

2.插槽的默认值

<div id="app">
  <cpn></cpn>
</div>

<template id="cpn">
  <div>
    <h2>我是组件</h2>
    <p>我是内容</p>
    <slot><span>我是默认值</span></slot>
  </div>
</template>
const vm = new Vue({
  el: '#app',
    components: {
        cpn: {
          template: '#cpn'
        }
    }
});        

在这里插入图片描述

3.多个值同时放入到组件进行替换时,一起作为替换元素

<div id="app">
  <cpn>
    <p>替换1</p>
    <i>替换2</i>
  </cpn>
</div>

<template id="cpn">
  <div>
    <h2>我是组件</h2>
    <p>我是内容</p>
    <slot><button>按钮</button></slot>
  </div>
</template>
const vm = new Vue({
  el: '#app',
      components: {
        cpn: {
          template: '#cpn'
        }
    }
});                      

在这里插入图片描述

4.具名插槽的使用

通过给插槽设置name属性准确找到需要替换的插槽

  <div id="app">
    <cpn><span slot="center">标题</span></cpn>
  </div>    

  <template id="cpn">
      <div>
            <slot name="left"><span>左边</span></slot>
            <slot name="center"><span>中间</span></slot>
            <slot name="right"><span>右边</span></slot>
      </div>
  </template>
      const vm = new Vue({
          el: '#app',
	    components: {
	      cpn: {
	        template: '#cpn'
	      }
            }
      });

在这里插入图片描述

5.作用域插槽

在父组件中无法访问到子组件中的数据,需要展示的数据还是子组件中的数据,但是展示的方式不同;通过设置slot-scope属性可以获取到子组件模板插槽中绑定的数据。

<div id="app">
    <cpn>
      <!-- 获取子组件中的数据 -->
      <!-- vue2.5.x版本以下必须用template包裹 版本以上用div也可以 -->
      <div slot-scope="slot">
        <span v-for="item in slot.num">{{item}}- </span>
      </div>
    </cpn>
</div>

<template id="cpn">
    <div>
      <slot :num="numArr">
        <ul>
          <li v-for="item in numArr">{{item}}</li>
        </ul>
      </slot>
    </div>
  </template>

const vm = new Vue({
      el: '#app',
      components: {
        cpn: {
          template: '#cpn',
          data() {
            return {
              numArr: [1,2,3,4,5,6,7]
            }
          }
        }
      }
 });

在这里插入图片描述

本文地址:https://blog.csdn.net/qq_43447509/article/details/107518313

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网