您的位置:首页 > Web前端 > Vue.js

vue组件之间的通信

2018-06-26 13:20 435 查看

实际开发一般都是用vue-cli中,本文就以vue-cli中的情境来描述。

一、父组件传递数据给子组件

父传子用props来实现,假设以下情境:


我们需要在灰色的父组件中操作改变白色的子组件的数字加减,并且可以在子组件中清空数字。我们就需要将父组件的操作的值传递给子组件。

父组件代码如下:

<template>
<div class="parent">
<!-- 绑定count传递给子组件 -->
<my-child :countToChild="count"></my-child>
<div class="box">
<button @click="increment">+</button>
<button @click="subtract">-</button>
</div>
</div>
</template>

import myChild from './child'

export default {
data() {
return {
count: 0
}
},
methods: {
increment() {
this.count++
},
subtract() {
this.count--
}
},
components: {
myChild
}
}
绑定两个加减事件用来操作数据,并绑定数据count传递给子组件。

子组件注册props用来接收该数据,子组件代码如下:

<template>
<div class="child">
<!-- 将数据渲染 -->
<div class="count">{{countToChild}}</div>
<button>clear</button>
</div>
</template>

export default {
props: [
'countToChild' //接收数据
]
}
或者props写成对象形式,更为清晰:
export default {
props: {
countToChild: {
type: Number, //说明传进来的数据为数字
default: 0, //默认为0,当页面初始化时会使用用该数据
}
}
}
这样就可以接收到父组件传过来的数据了。

二、子组件传递数据给父组件

但是当我们想要归零数据呢,在子组件试试:

<!-- 在子组件绑定一个clear事件 -->
<button @click="clear">clear</button>
methods: {
clear() {
this.countToChild = 0 //在这里注册clear事件
}
}
可以归零,但是控制台报错

子组件不能随意修改父组件的数字,因为当父组件重新渲染时这个值会被覆盖,最好在父组件修改值。

所以子组件需要告诉父组件需要更改值,这里使用自定义事件。

clear() {
this.$emit('clearThisCountInChild') //向父组件传递一个事件
}
}
<!-- 父组件接受事件并重命名为clearThisCountInParent -->
<my-child :countToChild="count" @clearThisCountInChild="clearThisCountInParent"></my-child>
clearThisCountInParent() { //在父组件中定义事件方法
this.count = 0 //归零
}
你也可以传参数:
clear() {
this.$emit('clearThisCountInChild', '完成', ''ok)
}
clearThisCountInParent(e, a) {
this.count = 0
console.log(e, a) //"完成 ok"
}

如果自定义事件过多会造成代码管理困难,同时自定义事件也很麻烦,非父子组件之间的通信还需要一个再创建一个实例作为中转,这就不利于我们开发效率,复杂或者频繁的数据传递推荐使用vuex统一管理,之后我会写一个关于vuex的理解。




阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: