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

2021-08-14 00:07:55 字數 3560 閱讀 5373

childa>

childb>

div>

template>

type="text/ecmascript-6">

import childa from './components/a.vue'

import childb from './components/b.vue'

export default

}script>

lang="stylus"

rel="stylesheet/stylus">

style>

建立字元件a

class="child-a">

div>

template>

type="text/ecmascript-6">

export default {}

script>

lang="stylus"

rel="stylesheet/stylus">

style>

建立子元件b

class="child-b">

div>

template>

type="text/ecmascript-6">

export default {}

script>

lang="stylus"

rel="stylesheet/stylus">

style>

childa>

childb>

div>

template>

type="text/ecmascript-6">

import childa from './components/a.vue'

import childb from './components/b.vue'

export default

},components:

}script>

lang="stylus"

rel="stylesheet/stylus">

style>

子元件a

class="child-a">我是元件a,接收到訊息:

div>

template>

type="text/ecmascript-6">

export default

}}script>

lang="stylus"

rel="stylesheet/stylus">

style>

執行結果如圖 

子元件向父元件傳遞資料用this,$emit()

子元件b

class="child-b">

div>

template>

type="text/ecmascript-6">

export default

},mounted ()

}script>

lang="stylus"

rel="stylesheet/stylus">

style>

childa>

v-on:msg="show">

childb

我是父元件,接受到訊息:}

div>

template>

type="text/ecmascript-6">

import childa from './components/a.vue'

import childb from './components/b.vue'

export default

},methods:

},components:

}script>

lang="stylus"

rel="stylesheet/stylus">

style>

結果如下 

還有另一種方法與兄弟元件通訊方式相同用eventbus

兄弟元件通訊用eventbus來實現 

新建乙個js檔案,來建立出我們的eventbus,把它命名為bus.js 

在元件a和元件b匯入就可以使用了 

bus.js

import vue from 'vue'

export default

new vue()

a元件

class="child-a">我是元件a,接收到b訊息:}div>

template>

type="text/ecmascript-6">

import bus from '../bus'

export default

},mounted () )

}}script>

lang="stylus"

rel="stylesheet/stylus">

style>

b元件

class="child-b">

div>

template>

type="text/ecmascript-6">

import bus from '../bus'

export default

},mounted ()

}script>

lang="stylus"

rel="stylesheet/stylus">

style>

結果如圖 

子元件向父元件傳遞資料也可以使用這種方法,仿兄弟元件通訊即可

參考文章

vue.js之路(4)——vue2.0s中eventbus實現兄弟元件通訊

vue2 0 父子元件通訊 兄弟元件通訊

父元件是通過props屬性給子元件通訊的來看下 父元件 content 注意這裡用駝峰寫法哦 data 子元件通過props來接受資料 第一種方法 props childcom 第二種方法 props 第三種方法 props 子元件與父元件通訊 vue2.0只允許單向資料傳遞,我們通過出發事件來改變...

vue2 0父子元件間通訊

父元件資料如何傳遞給子元件呢?可以通過props屬性來實現 父元件 這裡必須要用 代替駝峰data 子元件通過props來接收資料 方式1 props childmsg 方式2 props props 這樣呢,就實現了父元件向子元件傳遞資料.那麼,如果子元件想要改變資料呢?這在vue中是不允許的,因...

vue2 0父子元件間通訊

父元件資料如何傳遞給子元件呢?可以通過props屬性來實現 父元件 這裡必須要用 代替駝峰data 子元件通過props來接收資料 方式1 props childmsg 方式2 props props 這樣呢,就實現了父元件向子元件傳遞資料.那麼,如果子元件想要改變資料呢?這在vue中是不允許的,因...