Vue 之父子元件間的通訊

2021-10-02 17:32:53 字數 2805 閱讀 7754

兄弟元件間傳值:

一覽圖

1、靜態傳值

(1)在父元件中

在子元件佔位符中直接寫:引數名=「引數值」

="father"

>

this is father<

/h1>

<

!-- (靜態)父傳子:字串 --

>

"msg from father."

/>

<

/div>

<

/template>

// 引入子元件,必須

import child from '@/components/child.vue'

export default},

components:

}<

/script>(2)在子元件中

="child"

>

this is child<

/h1>

來自父元件的資料:

}<

/h1>

<

/div>

<

/template>

export default

,data()

}}<

/script>2、動態傳值

(1)在父元件中

使用 v-bind(語法糖 :)動態繫結資料,格式:v-bind:引數名=「變數名」 或 :引數名=「變數名」

="child"

>

this is child<

/h1>

<

!-- (動態)父傳子:變數 --

>

"message"

:pnum=

"num"

>

<

/child>

<

/div>

<

/template>

// 引入子元件,必須

import child from '@/components/child.vue'

export default},

components:

}<

/script>(2)在子元件中

="child"

>

this is child<

/h1>

for=

"item in pmessage"

>

}<

/h2>

}<

/h2>

<

/div>

<

/template>

export default

,data()

}}<

/script>(1)在子元件中

="child"

>

this is child<

/h1>

="toparent"

>toparent<

/button>

<

/div>

<

/template>

export default},

methods:}}

<

/script>(2)在父元件中

="father"

>

<

!-- v-on: 語法糖@,監聽子元件 --

>

="fromchild"

>

<

/child>

}<

/h2>

<

/div>

<

/template>

// 引入子元件,必須

import child from '@/components/child.vue'

export default},

methods:},

components:

}<

/script>(1)在父元件中

="father"

>

<

!-- 通過 ref 屬性 --

>

"mychild"

>

<

/child>

="clickparent"

>控制子元件<

/button>

<

/div>

<

/template>

// 引入子元件,必須

import child from '@/components/child.vue'

export default},

methods:},

components:

}<

/script>(2)在子元件中

="child"

>

this is child<

/h1>

}<

/h2>

<

/div>

<

/template>

export default},

methods:}}

<

/script>鳴謝 參考:

Vue2 0 之父子兄弟元件間通訊

childa childb div template type text ecmascript 6 import childa from components a.vue import childb from components b.vue export default script lang s...

Vue 父子元件間的通訊

前言在 vue 專案中父子元件的通訊是非常常見的,最近做專案的時候發現對這方面的知識還不怎麼熟練,在這邊做一下筆記,系統學習一下吧。父元件傳值給子元件,這個就比較常見了,直接用 props 就可以了。但是就算是 props 子元件那邊也有三種寫法,如下面 所示 父元件 子元件 1 簡單粗暴就給個名稱...

Vue 父子元件間的通訊

前言在 vue 專案中父子元件的通訊是非常常見的,最近做專案的時候發現對這方面的知識還不怎麼熟練,在這邊做一下筆記,系統學習一下吧。父元件傳值給子元件,這個就比較常見了,直接用 props 就可以了。但是就算是 props 子元件那邊也有三種寫法,如下面 所示 父元件 子元件 1 簡單粗暴就給個名稱...