VUE3之Component(一)

父组件传递给子组件

父组件传递给子组件:通过props属性

在子组件中定义props属性,props中可以定义字符串数组,也可以定义对象:

<template>
    <div>
        <h2>{{title}}</h2>
        <p>{{content}}</p>
    </div>
</template>

<script>
    export default {
        props: [
            "title",
            "content"
        ]
    }
</script>

在父组件中向子组件的属性传入值:

<template>
    <div>
        <show-message title="标题1" content="内容1"></show-message>
        <show-message title="标题2" content="内容2"></show-message>
        <show-message title="标题3" content="内容3"></show-message>
        <show-message :title="title" :content="content"></show-message>
        <show-message :title="message.title" :content="message.content"></show-message>
        <show-message v-bind="message"></show-message>
        
    </div>
</template>

<script>
import ShowMessage from "./ShowMessage.vue"
    export default {
        components:{
            ShowMessage
        },
        data(){
            return {
                title: "title",
                content:"content",
                message:{
                    title:"message title",
                    content:"message content"
                }
            }
        }
    }
</script>

props也可以传入一个对象(这也是常见的作法),可以定义是否是必须的与默认值:

        props:{
            title:String,
            content:{
                type:String,
                required:true,
                default:123
            },
            info:{
                type: Object,
                // 引用类型,需要写成函数
                default(){
                    return {name:"sk"}
                }
            }
        }

html在解析props时会忽略大小写,因此props最好统一使用小写。

非Prop的Attribute的传递:

非Prop的Attribute,即对于html组件都有的id、name、style等属性,它们在自定义的组件中并没有在props定义,对于这种属性,有三种处理方式:

Attribute根组件继承:当组件有单个根节点时,非Prop的Attribute将自动添加到根节点的Attribute中

        <show-message class="123" title="标题1" content="内容1"></show-message>

如果我们不希望组件的根元素继承attribute,可以在组件中设置inheritAttrs: false,可以通过$attrs来访问所有的非props的attribute

<script>
    export default {
        inheritAttrs:false
</script>
<template>
    <div>
        <h2 :class="$attrs.class">{{title}}</h2>
        <p>{{content}}</p>
    </div>
</template>

或直接使用对象:

<template>
    <div>
        <h2 v-bind="$attrs">{{title}}</h2>
        <p>{{content}}</p>
    </div>
</template>

如果有多个根节点的attribute,则需要显式地指明需要绑定在哪一个组件上,否则会报错:

<template>
    <h2 :id="$attrs.id">MultiRootElement</h2>
    <h2>MultiRootElement</h2>
    <h2>MultiRootElement</h2>
    <h2>MultiRootElement</h2>
</template>

发表评论