uni-app、Vue组件的使用-引用子组件、传值

复制代码
 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引入;

  ②在vuecomponents中注册;

  ③在父组件中直接引用,如:<bar></bar>

 2.传值给子组件

  ①在父组件通过v-bind传入一个值,如:<bar :title="title"></bar>

  ②在子组件中,通过props接收,如:

  props:{                  // 获取父组件传来的值
      title:{
          type:String,
          default:''
         }
      }
  },

 3.传值给父组件——通过this.$emit将方法和数据传递给父组件

  ①子组件:this.$emit('helloWorld') // 传值给父组件

  ②父组件:

1
2
3
helloWorld(){
    console.log( '我接收到子组件传递的事件了' )
}
posted @   ꧁执笔小白꧂  阅读(1232)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示
历史上的今天:
2021-01-19 Android项目可能遇到的问题
2021-01-19 C#-手机与电脑TCP通讯
点击右上角即可分享
微信分享提示