vue——组件间传值
一、父组件向子组件传值
父组件内设置要传的数据,在父组件中引用的子组件上绑定一个自定义属性并把数据绑定在自定义属性上,在子组件添加参数props接收即可。
<!-- 父组件 --> <template> <div> <child-com :user="userInfo"></child-com> </div> </template> <script> import childCom from '@/components/ChildCom.vue'; export default { data() { return { userInfo: { age: 18, likes: 'song', sex: 'man' } } }, computed: {}, components: { 'child-com': childCom }, mounted() { }, created(){}, methods: {} } </script> <style lang="scss"> </style> <!-- 子组件 --> <template> <div class="container"> <ul> <li v-for="(v, k) in user" :key="k">{{k}}——{{v}}</li> </ul> </div> </template> <script> export default { props:['user'] } </script> <style lang="scss"> </style>
效果:
二、子组件向父组件传值
子组件通过vue实例方法$emit进行触发并且可以携带参数,父组件监听使用@(v-on)进行监听,然后进行方法处理。
<!--子组件--> <template> <div class="container"> <van-button type="primary" @click="sendData">发送</van-button> </div> </template> <script> export default { data(){ return { userInfo: { userName: '徐林俊', age: 26, sex: 'man' } } }, methods: { sendData(){ this.$emit('updateUser', this.userInfo); } }, computed:{ } } </script> <style lang="scss"> </style> <!--父组件--> <!-- home --> <template> <div class="index-container"> <child-com @updateUser="updateUser"></child-com> <ul> <li v-for="(v, k) in userInfo" :key="k">{{k}} —— {{v}}</li> </ul> </div> </template> <script> import childCom from '@/components/ChildCom.vue'; export default { data() { return { userInfo: null } }, computed: {}, components: { 'child-com': childCom }, mounted() { }, created(){ }, methods: { updateUser(value){ this.userInfo = value; } } } </script> <style lang="scss"> </style>
效果:
三、子组件向子组件传值
bus总线传值
新建一个eventBus.js文件,然后在需要传值的子组件间引入,如下:
<!--组件1,负责发送数据--> <template> <div class="container"> <van-button type="primary" @click="sendData">发送</van-button> </div> </template> <script> import bus from '@/assets/js/eventBus.js'; export default { data(){ return { userInfo: { userName: '徐林俊', age: 26, sex: 'man' } } }, methods: { sendData(){ bus.$emit('updateUser', this.userInfo); } }, computed:{ } } </script> <style lang="scss"> </style> <!--组件2,负责接收数据--> <template> <div class="container"> <ul> <li v-for="(v, k) in userInfo" :key="k">{{k}} —— {{v}}</li> </ul> </div> </template> <script> import bus from '@/assets/js/eventBus.js'; export default { data(){ return { userInfo: null } }, methods: { }, mounted(){ bus.$on('updateUser', data => { this.userInfo = data; }) }, computed:{ } } </script> <style lang="scss"> </style> <!--父组件--> <template> <div class="index-container"> <child-com1></child-com1> <child-com2></child-com2> </div> </template> <script> import childCom1 from '@/components/ChildCom1.vue'; import childCom2 from '@/components/ChildCom2.vue'; export default { data() { return { } }, computed: { }, components: { 'child-com1': childCom1, 'child-com2': childCom2, }, mounted() { }, created(){ }, methods: { } } </script> <style lang="scss"> </style>
效果: