Vue之组件的自定义事件详解

在这里插入图片描述

<template>

<div >

<h2>{{msg}}</h2>

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

<School :getName="getName"/>

<Student :getStudentname="getStudentname"/>

<!-- 通过父组件给子组件绑定一个自定义事件:实现子给父传递数据 -->

<Age v-on:elderSex="demo"/>

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

<!-- <Student ref="student"/> -->

</div>

</template>

<script>

import School from './components/School.vue'

import Student from './components/Student.vue'

import Age from './components/Age.vue'

export default {

name:'App',

components:{ School,Student ,Age},

data(){

return {

msg:'你好,世界!'

}

},

methods:{

getName(name){

console.log('App收到了名字',name);

},

getStudentname(name1){

console.log('接收到了学生的姓名',name1);

},

demo(sex1){

console.log( 'demo被调用了',sex1);

}

},

// mounted() {

//绑定自定义事件

// this.$refs.student.$on('elderSex',this.schoolAge)

//绑定自定义事件(一次性)

// this.$refs.student.$once('elderSex',this.schoolAge)

// },

}

</script>

<style scoped>

</style>

<template>

<div class="demo">

<h2>学生姓名:{{name}}</h2>

<h2>学生年龄:{{age}}</h2>

<button @click="sendStudentname">把学生的名字给APP</button>

</div>

</template>

<script>

export default {

name: 'Student',

props: ['getStudentname'],

data() {

return {

name: '张三',

age: 19

}

},

methods: {

sendStudentname() {

this.getStudentname(this.name)

}

}

}

</script>

<style>

.demo {

background-color: skyblue;

}

</style>

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注的更多内容!

以上是 Vue之组件的自定义事件详解 的全部内容, 来源链接: utcz.com/p/240138.html

回到顶部