Vue元件間怎麼通訊?這篇文章盤點Vue2和Vue3的10種組件通訊方式,希望對大家有幫助!
Vue中元件通訊方式有很多,其中Vue2和Vue3實作起來也會有很多差異;本文將透過選項式API
組合式API
以及setup
三種不同實作方式全面介紹Vue2和Vue3的元件通訊方式。其中將要實現的通訊方式如下表所示。 (學習影片分享:vue影片教學)
方式 | Vue2 | Vue3 |
---|---|---|
#父傳子 | props | |
子傳父 | $emit | |
#父傳子 | #$attrs | |
$listeners | 無(合併到attrs方式) | |
#provide | provide | |
inject | inject |
props是元件通訊中最常用的通訊方式之一。父元件透過v-bind傳入,子元件透過props接收,以下是它的三種實作方式
//父组件 <template> <div> <Child :msg="parentMsg" /> </div> </template> <script> import Child from './Child' export default { components:{ Child }, data() { return { parentMsg: '父组件信息' } } } </script> //子组件 <template> <div> {{msg}} </div> </template> <script> export default { props:['msg'] } </script>
//父组件 <template> <div> <Child :msg="parentMsg" /> </div> </template> <script> import { ref,defineComponent } from 'vue' import Child from './Child.vue' export default defineComponent({ components:{ Child }, setup() { const parentMsg = ref('父组件信息') return { parentMsg }; }, }); </script> //子组件 <template> <div> {{ parentMsg }} </div> </template> <script> import { defineComponent,toRef } from "vue"; export default defineComponent({ props: ["msg"],// 如果这行不写,下面就接收不到 setup(props) { console.log(props.msg) //父组件信息 let parentMsg = toRef(props, 'msg') return { parentMsg }; }, }); </script>
//父组件 <template> <div> <Child :msg="parentMsg" /> </div> </template> <script setup> import { ref } from 'vue' import Child from './Child.vue' const parentMsg = ref('父组件信息') </script> //子组件 <template> <div> {{ parentMsg }} </div> </template> <script setup> import { toRef, defineProps } from "vue"; const props = defineProps(["msg"]); console.log(props.msg) //父组件信息 let parentMsg = toRef(props, 'msg') </script>
注意
props中資料流是單一項目的,即子元件不可改變父元件傳來的值
在組合式API中,如果想在子元件中用其它變數接收props的值時需要使用toRef將props中的屬性轉為回應式。
子元件可以透過emit發布一個事件並傳遞一些參數,父元件透過v-on進行這個事件的監聽
//父组件 <template> <div> <Child @sendMsg="getFromChild" /> </div> </template> <script> import Child from './Child' export default { components:{ Child }, methods: { getFromChild(val) { console.log(val) //我是子组件数据 } } } </script> // 子组件 <template> <div> <button @click="sendFun">send</button> </div> </template> <script> export default { methods:{ sendFun(){ this.$emit('sendMsg','我是子组件数据') } } } </script>
//父组件 <template> <div> <Child @sendMsg="getFromChild" /> </div> </template> <script> import Child from './Child' import { defineComponent } from "vue"; export default defineComponent({ components: { Child }, setup() { const getFromChild = (val) => { console.log(val) //我是子组件数据 } return { getFromChild }; }, }); </script> //子组件 <template> <div> <button @click="sendFun">send</button> </div> </template> <script> import { defineComponent } from "vue"; export default defineComponent({ emits: ['sendMsg'], setup(props, ctx) { const sendFun = () => { ctx.emit('sendMsg', '我是子组件数据') } return { sendFun }; }, }); </script>
//父组件 <template> <div> <Child @sendMsg="getFromChild" /> </div> </template> <script setup> import Child from './Child' const getFromChild = (val) => { console.log(val) //我是子组件数据 } </script> //子组件 <template> <div> <button @click="sendFun">send</button> </div> </template> <script setup> import { defineEmits } from "vue"; const emits = defineEmits(['sendMsg']) const sendFun = () => { emits('sendMsg', '我是子组件数据') } </script>
子元件使用$attrs可以取得父元件除了props傳遞的屬性和特性綁定屬性(class和style)之外的所有屬性。
子元件使用$listeners可以獲得父元件(不含.native修飾器的)所有v-on事件監聽器,在Vue3中已經不再使用;但是Vue3中的attrs不僅可以獲得父元件傳來的屬性也可以取得父元件v-on事件監聽器
//父组件 <template> <div> <Child @parentFun="parentFun" :msg1="msg1" :msg2="msg2" /> </div> </template> <script> import Child from './Child' export default { components:{ Child }, data(){ return { msg1:'子组件msg1', msg2:'子组件msg2' } }, methods: { parentFun(val) { console.log(`父组件方法被调用,获得子组件传值:${val}`) } } } </script> //子组件 <template> <div> <button @click="getParentFun">调用父组件方法</button> </div> </template> <script> export default { methods:{ getParentFun(){ this.$listeners.parentFun('我是子组件数据') } }, created(){ //获取父组件中所有绑定属性 console.log(this.$attrs) //{"msg1": "子组件msg1","msg2": "子组件msg2"} //获取父组件中所有绑定方法 console.log(this.$listeners) //{parentFun:f} } } </script>
//父组件 <template> <div> <Child @parentFun="parentFun" :msg1="msg1" :msg2="msg2" /> </div> </template> <script> import Child from './Child' import { defineComponent,ref } from "vue"; export default defineComponent({ components: { Child }, setup() { const msg1 = ref('子组件msg1') const msg2 = ref('子组件msg2') const parentFun = (val) => { console.log(`父组件方法被调用,获得子组件传值:${val}`) } return { parentFun, msg1, msg2 }; }, }); </script> //子组件 <template> <div> <button @click="getParentFun">调用父组件方法</button> </div> </template> <script> import { defineComponent } from "vue"; export default defineComponent({ emits: ['sendMsg'], setup(props, ctx) { //获取父组件方法和事件 console.log(ctx.attrs) //Proxy {"msg1": "子组件msg1","msg2": "子组件msg2"} const getParentFun = () => { //调用父组件方法 ctx.attrs.onParentFun('我是子组件数据') } return { getParentFun }; }, }); </script>
//父组件 <template> <div> <Child @parentFun="parentFun" :msg1="msg1" :msg2="msg2" /> </div> </template> <script setup> import Child from './Child' import { ref } from "vue"; const msg1 = ref('子组件msg1') const msg2 = ref('子组件msg2') const parentFun = (val) => { console.log(`父组件方法被调用,获得子组件传值:${val}`) } </script> //子组件 <template> <div> <button @click="getParentFun">调用父组件方法</button> </div> </template> <script setup> import { useAttrs } from "vue"; const attrs = useAttrs() //获取父组件方法和事件 console.log(attrs) //Proxy {"msg1": "子组件msg1","msg2": "子组件msg2"} const getParentFun = () => { //调用父组件方法 attrs.onParentFun('我是子组件数据') } </script>
注意
#Vue3中使用attrs呼叫父元件方法時,方法前需要加上on;如parentFun->onParentFun
provide:是一個對象,或是一個傳回對象的函數。裡麵包含要給子孫後代屬性
inject:一個字串數組,或是一個物件。取得父元件或更高層次的元件provide的值,既在任何後代元件都可以透過inject獲得
//父组件 <script> import Child from './Child' export default { components: { Child }, data() { return { msg1: '子组件msg1', msg2: '子组件msg2' } }, provide() { return { msg1: this.msg1, msg2: this.msg2 } } } </script> //子组件 <script> export default { inject:['msg1','msg2'], created(){ //获取高层级提供的属性 console.log(this.msg1) //子组件msg1 console.log(this.msg2) //子组件msg2 } } </script>
//父组件 <script> import Child from './Child' import { ref, defineComponent,provide } from "vue"; export default defineComponent({ components:{ Child }, setup() { const msg1 = ref('子组件msg1') const msg2 = ref('子组件msg2') provide("msg1", msg1) provide("msg2", msg2) return { } }, }); </script> //子组件 <template> <div> <button @click="getParentFun">调用父组件方法</button> </div> </template> <script> import { inject, defineComponent } from "vue"; export default defineComponent({ setup() { console.log(inject('msg1').value) //子组件msg1 console.log(inject('msg2').value) //子组件msg2 }, }); </script>
//父组件 <script setup> import Child from './Child' import { ref,provide } from "vue"; const msg1 = ref('子组件msg1') const msg2 = ref('子组件msg2') provide("msg1",msg1) provide("msg2",msg2) </script> //子组件 <script setup> import { inject } from "vue"; console.log(inject('msg1').value) //子组件msg1 console.log(inject('msg2').value) //子组件msg2 </script>
說明
provide/inject一般在深層元件嵌套中使用合適。一般在組件開發中用的居多。
$parent: 子元件取得父元件Vue實例,可以取得父元件的屬性方法等
$children: 父元件取得子元件Vue實例,是一個數組,是直接兒子的集合,但不保證子元件的順序
import Child from './Child' export default { components: { Child }, created(){ console.log(this.$children) //[Child实例] console.log(this.$parent)//父组件实例 } }
##注意父元件取得的$children並不是響應式的
//父组件 <template> <div> <Child ref="child" /> </div> </template> <script> import Child from './Child' export default { components: { Child }, mounted(){ //获取子组件属性 console.log(this.$refs.child.msg) //子组件元素 //调用子组件方法 this.$refs.child.childFun('父组件信息') } } </script> //子组件 <template> <div> <div></div> </div> </template> <script> export default { data(){ return { msg:'子组件元素' } }, methods:{ childFun(val){ console.log(`子组件方法被调用,值${val}`) } } } </script>
//父组件 <template> <div> <Child ref="child" /> </div> </template> <script> import Child from './Child' import { ref, defineComponent, onMounted } from "vue"; export default defineComponent({ components: { Child }, setup() { const child = ref() //注意命名需要和template中ref对应 onMounted(() => { //获取子组件属性 console.log(child.value.msg) //子组件元素 //调用子组件方法 child.value.childFun('父组件信息') }) return { child //必须return出去 否则获取不到实例 } }, }); </script> //子组件 <template> <div> </div> </template> <script> import { defineComponent, ref } from "vue"; export default defineComponent({ setup() { const msg = ref('子组件元素') const childFun = (val) => { console.log(`子组件方法被调用,值${val}`) } return { msg, childFun } }, }); </script>
//父组件 <template> <div> <Child ref="child" /> </div> </template> <script setup> import Child from './Child' import { ref, onMounted } from "vue"; const child = ref() //注意命名需要和template中ref对应 onMounted(() => { //获取子组件属性 console.log(child.value.msg) //子组件元素 //调用子组件方法 child.value.childFun('父组件信息') }) </script> //子组件 <template> <div> </div> </template> <script setup> import { ref,defineExpose } from "vue"; const msg = ref('子组件元素') const childFun = (val) => { console.log(`子组件方法被调用,值${val}`) } //必须暴露出去父组件才会获取到 defineExpose({ childFun, msg }) </script>
注意
透過ref取得子元件實例必須在頁面掛載完成後才能取得。 在使用setup語法糖時候,子元件必須元素或方法暴露出去父元件才能取得到mitt.js,原理還是EventBus
//组件1 <template> <div> <button @click="sendMsg">传值</button> </div> </template> <script> import Bus from './bus.js' export default { data(){ return { msg:'子组件元素' } }, methods:{ sendMsg(){ Bus.$emit('sendMsg','兄弟的值') } } } </script> //组件2 <template> <div> 组件2 </div> </template> <script> import Bus from './bus.js' export default { created(){ Bus.$on('sendMsg',(val)=>{ console.log(val);//兄弟的值 }) } } </script> //bus.js import Vue from "vue" export default new Vue()
npm i mitt -S
bus.js一樣新建
mitt.js檔案
import mitt from 'mitt' const Mitt = mitt() export default Mitt
//组件1 <template> <button @click="sendMsg">传值</button> </template> <script> import { defineComponent } from "vue"; import Mitt from './mitt.js' export default defineComponent({ setup() { const sendMsg = () => { Mitt.emit('sendMsg','兄弟的值') } return { sendMsg } }, }); </script> //组件2 <template> <div> 组件2 </div> </template> <script> import { defineComponent, onUnmounted } from "vue"; import Mitt from './mitt.js' export default defineComponent({ setup() { const getMsg = (val) => { console.log(val);//兄弟的值 } Mitt.on('sendMsg', getMsg) onUnmounted(() => { //组件销毁 移除监听 Mitt.off('sendMsg', getMsg) }) }, }); </script>
//组件1 <template> <button @click="sendMsg">传值</button> </template> <script setup> import Mitt from './mitt.js' const sendMsg = () => { Mitt.emit('sendMsg', '兄弟的值') } </script> //组件2 <template> <div> 组件2 </div> </template> <script setup> import { onUnmounted } from "vue"; import Mitt from './mitt.js' const getMsg = (val) => { console.log(val);//兄弟的值 } Mitt.on('sendMsg', getMsg) onUnmounted(() => { //组件销毁 移除监听 Mitt.off('sendMsg', getMsg) }) </script>
、程式設計基礎視頻)
以上是組件間怎麼通訊?盤點Vue組件通訊方式(值得收藏)的詳細內容。更多資訊請關注PHP中文網其他相關文章!