父子组件
概念:A组件中调用B组件,那么A组件就是父组件,B组件就是子组件
例:父组件中通过import的方式导入子组件,并在components属性中注册,然后父组件就可以用标签调用子组件。
<!-- 父组件 -->
<template>
<div>
<h1>我是父组件!</h1>
<child></child>
</div>
</template>
<script>
import Child from '../components/child.vue'
export default {
components: {Child},
}
</script>
<!-- 子组件 -->
<template>
<h3>我是子组件!</h3>
</template>
<script>
</script>
父组件 → 子组件:props
子组件的props选项能够接收来自父组件数据。没错,仅仅只能接收,props是单向绑定的,即只能父组件向子组件传递,不能反向。而传递的方式也分为两种:
①静态传递
父组件在子组件标签中加上一个自定义的属性,子组件中通过props选项声明一个相同的属性接受父组件传递的数据。
<!-- 父组件 -->
<template>
<div>
<h1>我是父组件!</h1>
<child message="我是子组件一!"></child> //通过自定义属性传递数据
</div>
</template>
<script>
import Child from '../components/child.vue'
export default {
components: {Child},
}
</script>
<!-- 子组件 -->
<template>
<h3>{{message}}</h3>
</template>
<script>
export default {
props: ['message'] //声明一个自定义的属性
}
</script>
②动态传递
动态数据可以用 v-bind 来实现。通过v-bind绑定props的自定义的属性,传递去过的就不是静态的字符串了,它可以是一个表达式、布尔值、对象等等任何类型的值。
<!-- 父组件 -->
<template>
<div>
<h1>我是父组件!</h1>
<!-- 这是一个 JavaScript 表达式而不是一个字符串。-->
<child v-bind:message="a+b"></child>
<!-- 用一个变量进行动态赋值。-->
<child v-bind:message="msg"></child>
</div>
</template>
<script>
import Child from '../components/child.vue'
export default {
components: {Child},
data() {
return {
a:'我是子组件二!',
b:112233,
msg: '我是子组件三!'+ Math.random()
}
}
}
</script>
<!-- 子组件 -->
<template>
<h3>{{message}}</h3>
</template>
<script>
export default {
props: ['message']
}
</script>
子组件 → 父组件:$emit
vm.$emit( event, arg )
$emit 绑定一个自定义事件event,当这个这个语句被执行到的时候,就会将参数arg传递给父组件,父组件通过@event监听并接收参数。
<!-- 父组件 -->
<template>
<div>
<h1>{{title}}</h1>
<child @getMessage="showMsg"></child>
</div>
</template>
<script>
import Child from '../components/child.vue'
export default {
components: {Child},
data(){
return{
title:''
}
},
methods:{
showMsg(title){
this.title=title;
}
}
}
</script>
<!-- 子组件 -->
<template>
<h3>我是子组件!</h3>
</template>
<script>
export default {
mounted: function () {
this.$emit('getMessage', '我是父组件!')
}
}
</script>