本文主要是介绍Vue之组件间的数据通信,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一、父组件与子组件传值
1.pros
通过 Prop 父组件向子组件传递数据。props是单向绑定的,即只能父组件向子组件传递,不能反向,是 Vue 的设计理念之单向数据流。
2.$emit
官方说法是触发当前实例上的事件。附加参数都会传给监听器回调。$emit 绑定一个自定义事件event,当这个这个语句被执行到的时候,就会将参数arg传递给父组件,父组件通过@event监听并接收参数。
3.$ref
通过$ref 实现通信,ref 是被用来给元素或子组件注册引用信息的。引用信息将会注册在父组件的 $refs 对象上。它主要用来调用子组件里的属性和方法,其实并不擅长数据传递。
4.实例
(1)父组件Main.vue
<template><div style="background: aliceblue;width: 50%;margin: 0 auto"><button @click="sendMsg">发送消息到子组件</button><div>子组件消息 :{{ msg }}</div><login ref="child" :title="title" @commituserresult="commitUserResult"> </login></div>
</template>
<script>
import login from "./login.vue";
export default {name: "parent",components: {login: login},data() {return {title: "登录中心",msg: "",};},methods: {//登录结果commitUserResult(msg) {this.msg = msg;},sendMsg() {this.$refs.child.getMsg(this.msg);}}
};
</script>
(2)子组件login.vue
<template><div style="background: lightblue;width: 50%;margin: 0 auto"><div>{{ title }}</div><div>用户:<input v-model="username" placeholder="请输入用户名"/></div><div>密码:<input v-model="password" placeholder="请输入密码"/></div><button @click="login">确认登录</button><div>来自父组件消息:{{msg}}</div></div>
</template><script>
export default {name: "child",props: {title: {type: String,default: "hello"},},data(){return{username: "",password: "",msg: ""}},methods: {//登录login() {if(this.username==='lss0555'){this.$emit("commituserresult", '登录成功,用户名:'+this.username);}else {this.$emit("commituserresult", '登录失败');}},//接收父组件的消息getMsg(msg){this.msg=msg}}
};
</script>
效果图
二、非父子组件间的数据传递,兄弟组件传值
eventBus,就是创建一个事件中心,相当于中转站,可以用它来传递事件和接收事件。小项目可以用这个,大项目建议用vuex,EvenBus参考文章
三、问题
1.父子组件传值,子组件改变值后父组件的值也改变的问题
-
现象
父组件传值给子组件,子组件改变传过来的值后,父组件的值也会跟着改变,即父子组件涉及到双向绑定。 -
解决
传值的时候不直接传数据源,而且经过拷贝或者定义新变量
比如数据源通过 ,JSON.stringfy()和JSON.parse() 转换
这篇关于Vue之组件间的数据通信的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!