vue父子傳值,兄弟傳值,子父傳值詳解
一、父組件向子組件傳值
1.父組件.vue
// 父組件中
<template>
<div>
<Child ref="child" :title="value"/>
</div>
</template>
<script>
export default {
data() {
return {
value: 'hello world!'
}
}
}
</script>
2.子組件.vue
// 父組件中
<template>
<div>
<span>{{title}}</span>
</div>
</template>
<script>
export default {
props: {
title: {
type: String,
default: ''
}
}
}
</script>
//title值為'hello world!
二、兄弟組件間傳值還可以通過中間件Bus
$emit 傳值
$on 接收
$off 刪除傳輸事件
1.A組件.js
this.$bus.$emit("flag",true)
2.B組件.js
mounted() {
this.$bus.$off('flag')
this.$bus.$on('flag', data=> {
this.flag= data
})
}
三、子組件向父組件傳值
1.父組件.js
<template>
<div>
<Child ref="child" @getTitle="getTitle"/>
</div>
</template>
<script>
import Child from './components/Child'
export default {
components: {
Child
},
data() {
return {
}
},
method:{
getTitle(data){
console.log(data)
}
}
}
</script>
打印結(jié)果為 hello xuliting
2.子組件.js
<template>
<div>
<span>{{title}}</span>
</div>
</template>
<script>
export default {
data() {
return {
title: 'hello xuliting'
}
},
mounted(){
this.getFun()
},
method:{
getFun(){
this.$emit("getTiltle",this.title)
}
}
}
</script>
總結(jié):
組件間也可以通過傳遞方法從而解決。例如父組件為A,子組件有B和C。
父組件A調(diào)用子組件B的方法定義為aFun,把a(bǔ)Fun傳遞給子組件C即可
這是在父組件中的組件C進(jìn)行方法傳遞
<C :a-fun="aFun" />
引用的則是在組件C,通過props
props: {
aFun: {
type: Function,
default: () => function() {}
}
}
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!
相關(guān)文章
使用ElementUI el-upload實(shí)現(xiàn)一次性上傳多個文件
在日常的前端開發(fā)中,文件上傳是一個非常常見的需求,尤其是在用戶需要一次性上傳多個文件的場景下,ElementUI作為一款非常優(yōu)秀的Vue.js 2.0組件庫,為我們提供了豐富的UI組件,本文介紹了如何使用ElementUI el-upload實(shí)現(xiàn)一次性上傳多個文件,需要的朋友可以參考下2024-08-08
一篇文章,教你學(xué)會Vue CLI 插件開發(fā)
這篇文章主要介紹了Vue CLI插件開發(fā),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04
vue-resourse將json數(shù)據(jù)輸出實(shí)例
這篇文章主要為大家詳細(xì)介紹了vue-resourse將json數(shù)據(jù)輸出實(shí)例,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-03-03
基于express中路由規(guī)則及獲取請求參數(shù)的方法
下面小編就為大家分享一篇基于express中路由規(guī)則及獲取請求參數(shù)的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-03-03
vue3+vite加載本地js/json文件不能使用require淺析
這篇文章主要給大家介紹了關(guān)于vue3+vite加載本地js/json文件不能使用require的相關(guān)資料,require 是屬于 Webpack 的方法,在v3+vite的項(xiàng)目里面并不適用,需要的朋友可以參考下2023-07-07
element-ui修改el-form-item樣式的詳細(xì)示例
在使用element-ui組件庫的時候經(jīng)常需要修改原有樣式,下面這篇文章主要給大家介紹了關(guān)于element-ui修改el-form-item樣式的詳細(xì)示例,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-11-11

