VUE之元件間通訊

2021-10-09 03:32:49 字數 3118 閱讀 2673

1.1 父元件向子元件傳值

父元件中:

// 父元件

>

:cityid

="cityid"

>

children

>

template

>

>

export

default}}

script

>

子元件:

// 子元件

>

>

}div

>

template

>

>

export

default}}

script

>

1.2 子元件向父元件傳值

父元件

// 父元件

>

:cityid

="cityid"

@callparent

="callparent"

>

children

>

template

>

>

import children from

"./children"

;export

default},

methods:}}

script

>

子元件:

// 子元件

>

@click

="solveclick"

>

}div

>

template

>

>

export

default

, props:},

methods:}}

script

>

2.1 通過父元件通訊
// 父元件

>

class

="parentnode"

>

@fromchildren1

="fromchildren1"

:mf2

="mf2"

>

children1

>

@fromchildren2

="fromchildren2"

:mf1

="mf1"

>

children2

>

div>

template

>

>

import children1 from

'./children1'

;import children2 from

'./children2'

;export

default

, methods:

, fromchildren2:

function

(message)}}

script

>

// 子元件1

>

>

children2 say:}

div>

@click

="sendmessage"

>

send message to childern2!botton

>

template

>

>

export

default},

props:},

methods:}}

script

>

// 子元件2

>

>

children1 say:}

div>

@click

="sendmessage"

>

send message to childern1!botton

>

template

>

>

export

default},

props:},

methods:}}

script

>

2.2 使用eventbus通訊
// main.js

import vue from

'vue'

export

const eventbus =

newvue()

newvue

()

子元件1:

// 子元件1

>

>

children2 say:}

div>

@click

="sendmessage"

>

send message to childern2!botton

>

template

>

>

import

from

'../main'

export

default},

methods:},

created()

)}}script

>

子元件2:

// 子元件2

>

>

children1 say:}

div>

@click

="sendmessage"

>

send message to childern1!botton

>

template

>

>

import

from

'../main'

export

default},

methods:},

created()

)}}script

>

vue元件間通訊

1 父元件向子元件傳遞資料,只需要props就行。設定資料並繫結到元件上。子元件用props接收,就能在元件內部使用獲取到的資料 反向通訊則需要在父級元件上自定義對應的方法,子元件使用 emit呼叫父元件方法,並上傳資料 content date content.vue date.vue 上面這個例...

vue元件間通訊

參考文章 vue父子元件間通訊可以用prop完成,跨級通訊則要用attrs來實現。1.attrs實現跨級通訊 父親元件 father元件 p msg1 p msg1 msg1 msg2 msg2 msg3 msg3 msg4 msg4 title 乙個標題 son1 div template imp...

vue元件間通訊

a元件要傳遞資料給b元件 a元件是有資料的,b元件是需要資料的 vue的各個元件data是不共享的,但是我們有時需要傳遞資料,那麼就可以使用vuex的store,store是乙個物件,裡面有個state,用來儲存多個元件需要使用的資料 我們先定義資料 在store的state中,定義資料 然後 在s...