VUE 组件通信

tech2022-10-07  97

组件之间的关系

父子关系非父子关系

组件通信-父子通信

父子通信,利用在父组件模板中,给子组件添加属性的方法进行通信,一旦添加了属性,那么在子组件中可以通过props进行接收

<template> <div> {{msg}} <Child :msg="msg"></Child> </div> </template> <script> export default { data () { return { msg: '父组件中的msg' } } } </script>

子组件

{ props: { msg: String } }

组件通信-子父通信

我们需要借助于原生事件去触发自定义事件(在子组件中触发),在父组件模板中找到子组件标签,并且监听该自定义事件,那么事件执行的函数中会有一个参数,这个参数就是触发自定义事件的携带的数据 子组件

const child = { template: ` <div> <button @click="clickHandler">点击传递数据</button> </div> `, methods: { clickHandler () { this.$emit('自定义事件名', 要传递的数据) } } }

父组件

const parent = { template: ` <div> <child @自定义事件名="要执行的函数"></child> </div> `, methods: { 要执行的函数 (param) { // 这个参数就是$emit时传递的数据 } } }

组件通信-非父子通信

非父子通信需要借助一个公共的vue实例(事件总线)

bus

const bus = new Vue()

组件1

const com1 = { template: ` <div> <button @click="clickHandler"></button> </div> `, methods: { clickHandler () { bus.$emit('自定义事件名', 数据) } } }

组件2

const com2 = { template: ` <div> </div> `, created () { bus.$on('自定义事件名', (data) => { // data就是传递的数据 }) } }
最新回复(0)