vue 2 元件之間傳值

2021-10-06 06:31:35 字數 1196 閱讀 2226

對vue2版本的元件之間傳值的乙個簡單整合:

父元件 =》 子元件: props 和 refs

- 

props:

//parent

this.$ref.helloworld.msg

子元件 =》 父元件 : 自定義事件

//child

this.$emit('send', msg)

//parent

兄弟元件: 通過共同祖輩搭橋 par

ent或

parent或

parent

或root

// brother1 

this.$parent.$on('foo', handle)

// brother2

this.$parent.$emit('foo')

祖先=>後代 provide/inject

// ancestor 

provide()

}// descendant

inject: ['msg']

後代 =》祖先 遞迴一直派發到root

// 定義乙個dispatch方法,指定要派發事件名稱和資料 

function dispatch(eventname, data)

}// 使用,helloworld.vue

this.$on('hello', this.sayhello)

任意兩個元件之間 事件匯流排 和 vuex

事件匯流排

class eventbus 

}$on(name, fn)

$emit(name)

}}//運用

main.js

vue.prototype.$bus = new eventbus()

this.$bus.$on('send', handlefn)

this.$bus.$emit('send')

vuex: 建立唯一的全域性資料管理者store,過載到vue例項,通過它管理狀態資料並通知元件狀態變更
3,4,5,6 都可以直接用$root

Vue2 元件封裝

接觸乙個前端框架,除了基礎的使用語法以外我們接下來都會很關心元件和復用的問題。以下就是個簡單的例子。下面是在父元件中引入子元件的 片段 booklist out container booklist container for book in books book book div button c...

vue2 0元件之間的傳值

1.父子元件 props props 需要注意的是,雖然的是單向的資料流,但是如果傳遞的是陣列或是物件這樣的引用型別,子元件資料變化,父元件的資料通也會變化 子元件 click export default props msgfromfather1 methods 父元件 動態繫結的資料 固定內容 ...

元件使用 2 元件傳值

點選事件觸發的時候 觸發父元件中的自定義事件 同時傳遞資料給 父元件 this.triggerevent 父元件自定義事件的名稱 要傳遞的引數 獲取索引 const e.currenttarget.dataset 觸發父元件中的自定義事件 同時傳遞資料給 this.triggerevent item...