vue最大的优点是好维护,复用率高。其中最主要的原因就是一个页面是有很多个子组件拼接起来的,座椅哪个模块需要优化改变,只需要去修改对应的组件即可。所以,各个组件之间肯定是需要相互联系,相互通信的。现在,我们来看下父子组件之间如何相互通信。
1:父组件向子组件输送数据,主要通过props属性。props 可以是数组或对象,用于接收来自父组件的数据。props 可以是简单的数组,或者使用对象作为替代,对象允许配置高级选项,如类型检测、自定义校验和设置默认值。
这是父组件,其中message是父组件想要传递给子组件的值。
这是子组件,其中,子组件想要接收到父组件传过来的值,主要就是通过props参数,该参数里主要说明想要接收哪个父组件传过来的值。
除此以外,还可以通过v-bind动态绑定想要传递给子组件的值
<template> <div class="parent"> <span>我是父组件</span> <child v-on:childToParentMsg="showChildToParentMsg" v-bind:parentToChild="parentMsg"></child> </div> </template> <script> import child from '../components/child' export default{ name:"parent", data(){ return { parentMsg:'我是父组件传递给子组件的数据' } }, methods: { showChildToParentMsg:function(data){ alert("父组件接收子组件的信息:"+data) } }, components: {child} } </script>
其中,通过v-bind指令绑定想要传递给子组件的变量信息,不要忘了在父组件中的data对象中注册该变量。
<template> <div class="child"> <span>我是子组件</span> <button v-on:click="childToParent">点我向父组件传值</button> <div id=""> 这是子组件接收的父组件传过来的的数据: <div style="color: red;">{{parentToChild}}</div> </div> </div> </template> <script> export default{ name: 'child', data(){ return {} }, methods: { childToParent(){ this.$emit("childToParentMsg", "我是子组件向父组件传的值"); } }, props:["parentToChild"] } </script>这里接收父组件的传值跟第一种是一样的,在props属性中指定要接收的变量名称,然后绑定到视图中。
2:子组件向父组件传输数据,主要是通过$emit自定义方法,将数据传递到父页面,父组件通过v-on来监听子组件通过$emit自定义的方法,这里子组件通过点击执行childParent方法,在该方法里,使用$emit自定义变量childToParentMsg,就像键值对一样,将要传递给子组件的值通过该变量传递。
<template> <div class="child"> <span>我是子组件</span> <button v-on:click="childToParent">点我向父组件传值</button> <div id=""> 这是子组件接收的父组件传过来的的数据: <div style="color: red;">{{parentToChild}}</div> </div> </div> </template> <script> export default{ name: 'child', data(){ return {} }, methods: { childToParent(){ this.$emit("childToParentMsg", "我是子组件向父组件传的值"); } }, props:["parentToChild"] } </script>
父组件主要是通过v-on指令监听子组件通过$emit自定义的变量名称,并且自定义方法,在该方法中传入参数,则改参数即代表子组件传递来的数据。
<template> <div class="parent"> <span>我是父组件</span> <child v-on:childToParentMsg="showChildToParentMsg" v-bind:parentToChild="parentMsg"></child> </div> </template> <script> import child from '../components/child' export default{ name:"parent", data(){ return { parentMsg:'我是父组件传递给子组件的数据' } }, methods: { showChildToParentMsg:function(data){ alert("父组件接收子组件的信息:"+data) } }, components: {child} } </script>
好了,现在看下效果图