1 //子組件 bar.vue 2 <template> 3 <div class="search-box"> 4 <div @click="say" :title="title" class="icon-dismiss"></div> 5 </div> 6 </template> 7 <script> 8 export default{ 9 props:{ // 獲取父組件傳來的值 10 title:{ 11 type:String, 12 default:'' 13 } 14 } 15 }, 16 methods:{ 17 say(){ 18 console.log('明天不上班'); 19 this.$emit('helloWorld') // 傳值給父組件 20 } 21 } 22 </script> 23 24 // 父組件 foo.vue 25 <template> 26 <div class="container"> 27 <bar :title="title" @helloWorld="helloWorld"></bar> 28 </div> 29 </template> 30 31 <script> 32 import Bar from './bar.vue' // 引用 33 export default{ 34 data(){ 35 return{ 36 title:"我是標題" 37 } 38 }, 39 methods:{ 40 helloWorld(){ 41 console.log('我接收到子組件傳遞的事件了') 42 } 43 }, 44 components:{ 45 Bar 46 } 47 </script>
1.引用:
①在需要使用的父組件中通過import引入;
②在vue的components中注冊;
③在父組件中直接引用,如:<bar></bar>
2.傳值給子組件
①在父組件通過v-bind傳入一個值,如:<bar :title="title"></bar>
②在子組件中,通過props接收,如:
props:{ // 獲取父組件傳來的值
title:{
type:String,
default:''
}
}
},
3.傳值給父組件——通過this.$emit將方法和數據傳遞給父組件
①子組件:this.$emit('helloWorld') // 傳值給父組件
②父組件:
helloWorld(){
console.log( '我接收到子組件傳遞的事件了' )
}
