子组件的引入
  • 新建Helloworld.vue页面,在export default中加入props,用于接收从父组件中传过来的message数据
1
2
3
4
5
6
props:{
message:{
type: Object,
required: true
}
},
  • 父组件App.vue使用import HelloWorld from "@/components/HelloWorld";引入子组件,并且在export default中增加`
1
2
3
4
5
6
7
8
9
10
export default {
data() {
return {
string: "ssss",
}
},
components: {
HelloWorld
}
}
  • 使用子组件
1
2
3
4
5
6
7
<template>
<div>
<HelloWorld :message="string"/>
<img src="./assets/logo.png" alt="logo">
<h1>{{ string }}</h1>
</div>
</template>
  • 使用:message = “string”,将父组件的string属性绑定给子组件的message

  • 子组件中显示父组件的message属性

1
2
3
4
5
  <template>
<div>
<span>这是父组件的 message: {{message}}</span>
</div>
</template>
Prop验证
  • 组件可以为props指定验证要求,为了定制prop的验证方式,可以为props中的值提供一个带有验证需求的对象,而不是一个字符串数组。例如:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    Vue.component('my-component',{
    props: {
    propA: number,
    propB: [String,Number],
    propC: {
    type: String,
    required: true
    },
    propD: {
    type=Number,
    default: 100
    }
    }
    )
  • 当prop验证失败时,Vue将会产生一个控制台的警告

自定义事件
  • 父组件是使用props传递数据给子组件,但如果子组件要把数据传递回去,就需要使用自定义事件。

  • 使用$emit触发事件

  • 父组件可以在使用子组件的地方直接用v-on来监听子组件触发的事件

    注意:data必须是一个函数