vue父子組件傳值以及通訊

1.子組件的使用

1.編寫子組件
2.在需要使用的父組件中通過import引入
3.在vue的components中注冊
4.在模板中使用

子組件向父組件傳值

//子組件 bar.vue
<template>
    <div class="search-box">
        <div @click="say" :title="title" class="icon-dismiss"></div>
    </div>
</template>
<script>
export default{
props:{
    title:{
       type:String,
       default:''
      }
    }
},
methods:{
    say(){
       console.log('明天不上班');
       this.$emit('helloWorld')
    }
}
</script>

// 父組件 foo.vue
<template>
  <div class="container">
    <bar :title="title" @helloWorld="helloWorld"></bar>
  </div>
</template>

<script>
import Bar from './bar.vue'
export default{
data(){
    return{
        title:"我是標題"
    }
},
methods:{
    helloWorld(){
        console.log('我接收到子組件傳遞的事件了')
    }
},
components:{
    Bar
}
</script>
2.父子組件間通信

父組件向子組件傳遞數(shù)據(jù)
只需要在父組件通過v-bind傳入一個值,在子組件中,通過props接收,即可完成數(shù)據(jù)的傳遞,示例:

// 父組件 foo.vue
<template>
  <div class="container">
    <bar :title="title"></bar>
  </div>
</template>
<script>
import Bar from './bar.vue'
export default{
  data(){
    return{        
        title:"我是標題"
    }
},
components:{
    Bar
}
</script>

// 子組件bar.vue
<template>
  <div class="search-box">
     <div :title="title" ></div>
  </div>
</template>
<script>
export default{
    props:{
        title:{
           type:String,
           default:''
          }
        }
   }
</script>

子組件和父組件通信可以通過this.$emit將方法和數(shù)據(jù)傳遞給父組件。

父組件調(diào)用子組件的方法

vue會給子組件添加一個ref屬性,通過this.$refs.ref的值便可以獲取到該子組件,然后便可以調(diào)用子組件中的任意方法,例如:

//子組件
<bar ref="bar"></bar>

//父組件
this.$ref.bar.子組件的方法
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容