首先需要分别创建父组件和子组件
//父组件
<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>
父组件通过import的方式导入子组件,并在components属性中注册,然后子组件就可以用标签的形式嵌进父组件了。
一、首先,我们来看props是如何进行数据传递的:
子组件的props选项能够接收来自父组件数据。没错,仅仅只能接收,props是单向绑定的,即只能父组件向子组件传递,不能反向。而传递的方式也分为两种:
1、静态传递
//父组件
<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>
2、动态传递
//父组件
<template>
<div>
<h1>我是父组件!</h1>
<child message = "我是子组件一"></child>
---------
<child v-bind:message = "aa +bb"></child>
-------
<child v-bind:message = "msgs"></child>
</div>
</template>
<script>
import Child from '../components/child.vue'
export default {
components: {Child},
data(){
return{
aa:'我是子组件二',
bb:121233,
msgs:"我是子组件三"
}
}
}
</script>
//子组件
<template>
<h3>{{message}}</h3>
</template>
<script>
export default {
props: ['message'] //声明一个自定义的属性
}
</script>
二、接下来看$ref来实现通信
<!-- 父组件 -->
<template>
<div>
<h1>我是父组件!</h1>
<child ref="msg"></child>
</div>
</template>
<script>
import Child from '../components/child.vue'
export default {
components: {Child},
mounted: function () {
console.log( this.$refs.msg);
this.$refs.msg.getMessage('我是子组件一!')
}
}
</script>
<!-- 子组件 -->
<template>
<h3>{{message}}</h3>
</template>
<script>
export default {
data(){
return{
message:''
}
},
methods:{
getMessage(val){
this.message=val;
}
}
}
</script>
如果ref用在子组件上,指向的是组件实例,可以理解为对子组件的索引,通过$ref可能获取到在子组件里定义的属性和方法。
如果ref在普通的 DOM 元素上使用,引用指向的就是 DOM 元素,通过
r
e
f
可
能
获
取
到
该
D
O
M
的
属
性
集
合
,
轻
松
访
问
到
D
O
M
元
素
,
作
用
与
J
Q
选
择
器
类
似
。
三
、
通
过
ref可能获取到该DOM 的属性集合,轻松访问到DOM元素,作用与JQ选择器类似。 三、通过
ref可能获取到该DOM的属性集合,轻松访问到DOM元素,作用与JQ选择器类似。三、通过emit实现通信
vm.
e
m
i
t
(
e
v
e
n
t
,
a
r
g
)
,
emit( event, arg ),
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>