国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

Vue組件間通信方法總結(父子組件、兄弟組件及祖先后代組件間

2024-05-06 15:40:31
字體:
來源:轉載
供稿:網友

前言

除了使用 Vuex 方法外,vue 提供了各種各樣的組件間通信的方案。文章整理一下父子組件、兄弟組件、祖先后代組件間是如何通信的。 💬

🌊 父子組件通信

props 和 $emit 父子組件通信

子組件有時需要與父組件進行溝通,溝通的方式就是子組件 emit 事件,父組件通過監聽這個事件來做進一步動作。而父組件與子組件通信則使用 props

假設這里有一個父組件并引入了一個子組件 my-comp:

<my-comp v-for="msg in msgs" :key="msg.id" :msg="msg"></my-comp>

父組件有一系列 msg 數據需要通過子組件渲染,將 msg 作為 prop 傳遞給子組件即可:

import MyComp from '@/components/MyComp.vue'export default { name: 'home', components: { MyComp }, data () { return { msgs: [{ id: 1, data: 'hello js' }, { id: 2, data: 'css world' }, { id: 3, data: 'animated style' }] } }}

我們通過點擊子組件每一項觸發一個事件,父組件監聽這個事件去動態改變子組件的 color 樣式,這就是父組件監聽子組件事件,事件處理函數可以從子組件傳遞值給父組件:

<my-comp v-for="msg in msgs" :key="msg.id" :msg="msg" :colored="colored" @handle-change-color="handleChangeColor"></my-comp>

首先增加一個事件 handle-change-color 當這個事件被觸發時修改名為 color 的 data,然后將 colored 通過 props 傳入到子組件:

import MyComp from '@/components/MyComp.vue'export default { name: 'home', components: { // 注冊組件 MyComp }, data () { return { colored: false, // 狀態 msgs: [{ id: 1, data: 'hello js' }, { id: 2, data: 'css world' }, { id: 3, data: 'animated style' }] } }, methods: { handleChangeColor () { this.colored = !this.colored // 監聽事件動態改變 colored } // handleChangeColor (param) { // 子組件觸發的事件可能包含參數 }}

然后編輯子組件:

<div> <div @click="handleClick" :style="{color}"> {{msg.id}} - {{msg.data}} ⭕ </div></div>

首先渲染數據,并監聽 click 點擊事件,當點擊觸發事件處理函數 handleClick

export default { name: 'MyComp', computed: { color () { // color 為樣式 return this.colored ? 'red' : 'black' // 根據父組件傳入的 props 動態修改樣式 } }, props: ['msg', 'colored'], methods: { handleClick (e) { this.$emit('handle-change-color') // 使用 $emit 方法觸發父組件 handle-change-color 事件 // this.$emit('handler', 'param') // 還可以給事件傳遞參數 } }}

子組件接收 colored 父組件傳遞來的 prop,返回一個計算后的屬性 color,根據 colored 返回不同樣式。handleClick 處理當子組件元素被點擊時 $emit 派發父組件的 handle-change-color 事件

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 凌海市| 彭泽县| 博兴县| 永宁县| 纳雍县| 宜君县| 包头市| 保山市| 清水县| 清苑县| 奇台县| 菏泽市| 五台县| 博兴县| 泰兴市| 平湖市| 济源市| 诸城市| 宿州市| 浦东新区| 恩平市| 安福县| 营口市| 全州县| 沽源县| 汤原县| 石渠县| 晋州市| 哈尔滨市| 临安市| 漳浦县| 桂阳县| 博罗县| 汝南县| 涟水县| 沂南县| 青浦区| 防城港市| 勐海县| 明溪县| 宜州市|