初识vue 2.0(7):使用slot复用模版

在vue中,将父组件的内容放到子组件指定的位置叫做内容分发,类似将父组件的html传到子组件中,达到子组件控制父组件的目的。

例如:我们要开发多个弹窗,这些弹窗有公共的头部、边框、关闭按钮等内容。如果每个弹窗,独立去实现,就会产生很多冗余代码。

于是我们可以使用slot(插槽)功能。

1. 创建一个父组件Box.vue,实现弹窗的基础功能,并且使用slot占位。

<template>
    <div class="box">
        <h2>{{ msg }}</h2>
        <h6>{{ slotData }}</h6>
        <slot></slot>
    </div>
</template>
<script>
export default {
    name: 'box',
    props: ["slotData"],
    data () {
        return {
            msg: '我是box模块'
        }
    }
}
</script>
<style lang="css">
.box{
    border: 1px solid #FFA200;
    width: 300px;
}  
</style>

2. 创建多个子组件Game.vue等,实现各自不同的内容,并在子组件中引入父组件,子组件通过props向父组件中传递数据。

<template>
<Box :slotData="hello">
    <div class="game">
        <h2>{{ msg }}</h2>
    </div>
</Box>
</template>
<script>
import Box from './Box'
export default {
    name: 'game',
    components: {
        Box,
    },
    data () {
        return {
            msg: '我是game模块',
            hello:"hello box"
        }
    }
}
</script>
<style lang="css">
.game{
    border: 1px solid #00FF00;
    width: 200px;
}  
</style>

按照props规则,上述的父组件并不是真的父组件,只是嵌套在子组件外层的公共部分。

猜你喜欢

转载自www.cnblogs.com/phptree/p/9766482.html