目录
(2)发送事件 假设有两个兄弟组件firstCom和secondCom:
1. props / $emit
父组件通过props的方式向子组件传递数据,而通过$emit 子组件可以向父组件通信:
- 父传子:父组件通过import引入子组件,并注册,在子组件标签上添加要传递的属性,子组 件通过props接收,接收有两种形式一是通过数组形式[‘要接收的属性’ ],二是通过对象形式{ }
- 子传父:父组件向子组件传递事件方法,子组件通过
$emit触发事件,回调给父组件
props的特点:
- props只能是父组件向子组件进行传值,props使得父子组件之间形成一个单向的下行绑定。子组件的数据会随着父组件的更新而响应式更新;但是子组件无法引起父组件的数据更新。
- props可以显示定义一个或一个以上的数据,对于接收的数据,可以是各种数据类型,同样也可以是传递一个对象或函数。
- props属性名规则:若在props中使用驼峰形式,模板中标签需要使用短横线的形式来书写。
代码示例:
父传子(prop的用法)
父组件:
<template>
<div id="father">
<son :msg="msg" :fn="myFunc"></son>
</div>
</template>
<script>
import son from "./son.vue";
export default {
name: "father",
components: {
son
},
data() {
msg: "我是父组件";
},
methods: {
myFunc() {
console.log("我是父组件的方法");
}
}
};
</script>
子组件:
<template>
<div id="son">
<p>{
{msg}}</p>
<button @click="fn">按钮</button>
</div>
</template>
<script>
export default {
name: "son",
props: ["msg", "fn"]
};
</script>
子传父($emit的用法)
$emit 绑定一个自定义事件,当这个事件被执行的时候就会将参数传递给父组件,而父组件通过v-on监听并接收参数
父组件:
<template>
<div id="father">
<son :arrList="arrList" @changeIndex="changeIndex"></son>
<p>{
{currentIndex}}</p>
</div>
</template>
<script>
import son from './son.vue'
export default {
name: 'father',
components: { son},
data() {
return {
currentIndex: -1,
arrList: ['龙族', '绘梨衣', '前端','后端']
}
},
methods: {
changeIndex(index) {
this.currentIndex = index
}
}
}
</script>
子组件:
<template>
<div>
<div v-for="(item, index) in arrList" :key="index" @click="emitIndex(index)">{
{item}}</div>
</div>
</template>
<script>
export default {
props: ['arrList'],
methods: {
emitIndex(index) {
this.$emit('changeIndex', index) // 触发父组件的方法,并传递参数index
}
}
}
</script>
2.ref / $refs
ref:这个属性用在子组件上,它的引用就指向了该子组件的实例,可以通过实例来访问组件的数据和方法;如果在普通的 DOM 元素上使用,引用指向的就是 DOM元素。
父组件:
<template>
<child ref="child"></component-a>
</template>
<script>
import child from './child.vue'
export default {
components: { child },
mounted () {
console.log(this.$refs.child.name); // mySon
this.$refs.child.sayHello(); // Hello father!
}
}
</script>
子组件:
<template>
<div id="app"></div>
</template>
<script>
export default {
name:'child',
data () {
return {
name: 'mySon'
}
},
methods: {
sayHello () {
console.log('Hello father!')
}
}
}
</script>
Vue组件通信:props,$emit,ref,eventBus,Vuex详解

最低0.47元/天 解锁文章
1072

被折叠的 条评论
为什么被折叠?



