父子组件通信
1.父组件和子组件通信
props
父组件给子组件绑定属性,子组件通过
props
属性来接收传递的数据
通过 Prop 向子组件<blog-post>
传递数据
<!-- 子组件 -->
Vue.component('blog-post', {
props: ['post'],
template: `
<div class="blog-post">
<h3>{{ post.title }}</h3>
<div v-html="post.content"></div>
</div>
`
})
复制代码
<!-- 父组件 -->
<blog-post
v-for="post in posts"
:key="post.id"
:post="post"
></blog-post>
复制代码
<blog-post :post="postData"></blog-post>
复制代码
props
可以是一个字符串、数值、布尔、数组、对象或对象中的所有属性
props: {
title: String,
likes: Number,
isPublished: Boolean,
commentIds: Array,
author: Object,
callback: Function,
contactsPromise: Promise // or any other constructor
}
复制代码
- 父组件访问子组件:
$ref
如果ref用在子组件上,指向的是组件实例,可以理解为对子组件的索引,通过$ref可能获取到在子组件里定义的属性和方法。
如果ref在普通的 DOM 元素上使用,引用指向的就是 DOM 元素,通过$ref可能获取到该DOM的属性集合,轻松访问到DOM元素,作用与JQ选择器类似。
<!-- 父组件 -->
<h1>我是父组件!</h1>
<child ref="msg"></child>
<script>
this.$refs.msg.getMessage('我是子组件一')
</script>
复制代码
<!-- 子组件 -->
<template>
<h3>{{message}}</h3>
</template>
<script>
export default {
data(){
return{
message:''
}
},
methods:{
getMessage(m){
this.message=m;
}
}
}
</script>
复制代码
- 父组件访问子组件:
$children
当前实例的直接子组件。需要注意
$children
并不保证顺序,也不是响应式的。如果使用$childre
来进行数据绑定,考虑使用一个数组配合 v-for 来生成子组件,并且使用 Array 作为真正的来源。
2.子组件和父组件通信
$emit
子组件通过调用$emit方法可以和父组件进行通信
父级组件可以通过 v-on 监听子组件实例的任意事件
<!--父组件 -->
<div id="blog-posts-events-demo">
<div :style="{ fontSize: postFontSize + 'em' }">
<blog-post
v-for="post in posts"
:key="post.id"
:post="post"
@enlargeText="postFontSize += 0.1"
></blog-post>
</div>
</div>
复制代码
子组件可以通过调用$emit方法并传入事件名称来触发一个事件
<!--子组件 -->
Vue.component('blog-post', {
props: ['post'],
template: `
<div class="blog-post">
<h3>{{ post.title }}</h3>
<button @click="$emit('enlargeText')">
Enlarge text
</button>
<div v-html="post.content"></div>
</div>
`
})
复制代码
- 子组件访问父组件:$parent
$parent表示父组件的实例,该属性只读
- 子组件访问根组件:$root
表示当前组件树的根 Vue 实例,即new Vue({…根组件内容})。
如果当前实例没有父实例,此实例将会是其自己。
Vue子组件可以通过$root属性访问父组件实例的属性和方法
同级组件通信
- 同级组件不能直接传值,需要一个中间桥梁,可以先将数据传递给公共的父组件,然后父组件再将数据传递给需要的子组件。
- 一般大型的项目,推荐使用Vuex来管理组件之间的通信
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END