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('我接收到子组件传递的事件了') }