您的位置:首页 > Web前端 > Vue.js

vue 插槽理解

2020-02-02 03:13 573 查看

插槽,顾名思义留一个坑在组件中,然后动态的去填坑,例如:

//Child.vue  子组件

<template>
<div>
<slot></slot>
</div>
</template>
<script>
</script>
<style lang="">

</style>

//Parent.vue   引入子组件的文件

<template>
<div>
<my-child>
123
</my-child>
</div>
</template>
<script>
import Child from './Child'
export default {
components: {myChild: Child}
}
</script>
<style lang="">

</style>

//这个时候,我们的页面就会显示123,在Child.vue中我们使用的slot就是坑位,在Parent.vue中,引用组件中传入的123就是填坑的内容,因为slot没有命名,这里称为不具名插槽

那么现在咱们来看看具名插槽的写法

//Child.vue  子组件

<template>
<div>
<h1>--------------分割线--------------------</h1>
<slot name="navBar"></slot>
<h1>--------------分割线--------------------</h1>
<slot name="endBar"></slot>
<h1>--------------分割线--------------------</h1>
</div>
</template>
<script>
</script>
<style lang="">

</style>

//Parent.vue   引入子组件的文件

<template>
<div>
<my-child>
<template slot="navBar">
234
</template>
<template slot="endBar">
345
</template>
</my-child>
</div>
</template>
<script>
import Child from './Child'
export default {
components: {myChild: Child}
}
</script>
<style lang="">

</style>

//这个时候我们需要注意的是,在Child.vue中,用name来标识该插槽slot,而在使用中,我们用<template slot="表示名">来传入指定的插槽

还有一个插槽方式叫做作用域插槽

//Child.vue  子组件

<template>
<div>
<!-- 这里的test作为键  ParentFromData 作为值返回给父组件 {test:  'Hello Vue!!!'}-->
<slot :test="ParentFromData"></slot>
</div>
</template>
<script>
export default {
prop: ['ParentFromData']
}
</script>
<style lang="">

</style>

//Parent.vue   引入子组件的文件

<template >
<div>
<my-child :ParentFromData='data'>
<template slot-scope='ChildFromData'>
{{ChildFromData}}
</template>
</my-child>
</div>
</template>
<script>
import Child from './Child'
export default {
data(){
return{
data: 'Hello Vue!!!'
}
}
components: {myChild: Child}
}
</script>
<style lang="">

</style>

//此时的流程是,Parent.vue通过  prop 将 ParentFromData传递给Child.vue,而Child.vue拿到值以后将值赋值给test  形成键值对{test: 'Hello Vue!!!'} 返回给Parent.vue,从而页面显示的结果为{test: 'Hello Vue!!!'}
//我发现一个vue文件里面只能有一个作用域插槽

转载于:https://www.cnblogs.com/yzyh/p/10124167.html

  • 点赞
  • 收藏
  • 分享
  • 文章举报
dengye7077 发布了0 篇原创文章 · 获赞 0 · 访问量 421 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: