1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > Vue-父子组件间传值(props 自定义事件+$emit() ref)

Vue-父子组件间传值(props 自定义事件+$emit() ref)

时间:2024-05-13 06:22:51

相关推荐

Vue-父子组件间传值(props 自定义事件+$emit() ref)

主要是子组件给父组件传值

一、案例🌞

School.vue和Student.vue子组件要和父组件App之间产生数据交互

需求1:点击“把学校名给App”按钮将学校名传给App

实现:

APP.vue

(1)App里定义获取学校名的方法getSchoolName

methods:{getSchoolName(name){console.log('App收到了学校名:',name)}}

(2)通过在School组件标签里添加getSchoolName方法将该方法传递给School组件

<School :getSchoolName="getSchoolName"/>

School.vue

(3)School组件需要用props来接收这个方法类型的值

(4)按钮绑定sendSchoolname( )方法的click事件,methods里添加该方法用来发送name,同时调用props里接收来的getSchoolName( )方法来传参

<button @click="sendSchoolName">把学校名给App</button>//...export default {name:'School',props:['getSchoolName'],data() {return {name:'哈佛',address:'美国',}},methods: {sendSchoolName(){this.getSchoolName(this.name)}},}

需求2:点击“把学生名给App”按钮将学生名传给App

通过父组件给子组件绑定一个自定义事件实现

实现1:使用@或v-on

App.vue

(1)给Student组件的实例对象vc上绑定自定义事件atguigu,如果有人触发了该事件,getStudentName函数就会被调用。

<Student v-on:atguigu="getStudentName"/>

(2)在methods中配置getStudentName( )

getStudentName(name,...params){console.log('App收到了学生名:',name,params)this.studentName = name}

Student.vue

(3)按钮绑定sendStudentname( )方法的click事件,methods里添加该方法,调用$emit( )方法触发事件。

<button @click="sendStudentlName">把学生名给App</button>methods: {sendStudentlName(){//触发Student组件实例身上的atguigu事件,触发后sendStudentname()被调用,同时接收namethis.$emit('atguigu',this.name,666)// this.$emit('demo')// this.$emit('click')}}

实现 2:使用ref(更灵活)

App.vue

(1)在Student子组件标签里添加ref注册引用信息。通过this.$refs.student获取Student组件的实例对象。(里面的student相当于组件Student的id)

<Student ref="student" @click.native="show"/>

(2)添加生命周期钩子mounted()

mounted() {this.$refs.student.$on('atguigu',this.getStudentName) //绑定自定义事件// this.$refs.student.$once('atguigu',this.getStudentName) //绑定自定义事件(一次性)},

PS:ref属性:

1. 被用来给元素或子组件注册引用信息(id的替代者)

2. 应用在html标签上获取的是真实DOM元素,应用在组件标签上是组件实例对象(vc)

3. 使用方式:

1. 打标识:```<h1 ref="xxx">.....</h1>``` 或 ```<School ref="xxx"></School>```

2. 获取:```this.$refs.xxx```

对比:方法2比方法1更灵活,原因在于如果想等App组件挂载完毕后等5秒钟才给Student子组件绑定自定义事件,用方法1就不能实现,因为模板解析时,会给Student瞬间绑定。

二、总结

子组件给父组件传值通常来说有三种方法:

通过父组件给子组件传递函数类型的props实现:子给父传递数据

通过父组件给子组件绑定一个自定义事件实现:子给父传递数据(第一种写法,使用@或v-on)

通过父组件给子组件绑定一个自定义事件实现:子给父传递数据(第二种写法,使用ref)

props适用于:

(1)父组件 ==> 子组件 通信

(2)子组件 ==> 父组件 通信(要求父先给子一个函数)

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。