vue-day48---组件的自定义是将

发布时间 2023-07-27 00:00:14作者: 雪落无痕1

1.App.vue

<template>
<div >
<h1>{{ msg }}你的名字是{{ studentName }}</h1>
<!--通过父组件给子组件传递函数的props 实现 子给父传数据-->
<School :receiveSchoolName="receiveSchoolName"></School>
<!-- v-on 在student 组件标签上 所以说是在给 student组件的实例对象vc 上绑定事件,事件名字是smytest
有人触发了这个事件,receiveStuedntName 函数就会被调用
-->
<!--通过父组件给子组件绑定一个自定义事件实现 子给父传数据 第一种写法 使用@ 或者v-on -->
<!-- <Student v-on:smytest="receiveStuedntName" @demo="m1"></Student> -->
<!--触发一次-->
<!-- <Student v-on:smytest.once="receiveStuedntName"></Student> -->

<!--通过父组件给子组件绑定一个自定义事件实现 子给父传数据 第二种写法 使用ref-->
<Student ref="student" @click.native="show"></Student>
 
</div>
 
 
</template>

<script>
//样式的引入和这里有关系
import School from './components/School.vue';
import Student from './components/Student.vue';


export default {
name: 'App',
components: {
School,
Student,
 
},
data(){
return {
msg:"欢迎学习vue",
studentName:""
}
 
},

methods:{
receiveSchoolName(schoolName){
console.log("app组件收到了学校的名字信息",schoolName);
},


//receiveStuedntName(studentName,...a){ 接收多个参数,第一个参数 后面的几个参数全部封装为数组
receiveStuedntName(studentName){
this.studentName=studentName;
console.log("app组件收到了学生的名字信息",studentName);
},
m1(){
console.log("demo事件被触发了");
},
show(){
alert("1234");
}

},
mounted(){
//this.$refs.student.$on('smytest',this.receiveStuedntName)
// 或者使用箭头函数
this.$refs.student.$on('smytest',(name,params)=>{
this.studentName=name;
console.log("app组件收到了学生的名字信息",name);
})
 
}
 

 
}
</script>

<style scoped>

</style>



 

2.Student.vue

 

 

<template>
<div class="student">
 
<h2>学生姓名{{name}}</h2>
<h2>学生性别{{sex}}</h2>
<h2>当前求和为{{number}}</h2>
<button @click="add">点我number++</button>
<button @click="sendStudentName">点我将学生名字传递给App</button>

<button @click="unbind">解绑自定义事件</button>
 
<button @click="death">销毁当前student组件的实例</button>
 
</div>
</template>


<script>


export default {
name:"Student",
data() {
return {
 
name:"张三",
sex:'男',
number:0
}
},

methods: {
add(){
console.log("add函数被调用了");
this.number++;
},
sendStudentName(){
// 触发Student 组件实例对象上的 smytest 事件
// 如果参数过多 1.可以把数据封装为对象
// 2. this.$emit('smytest',this.name,99999,8888,4444)
this.$emit('smytest',this.name,99999)
this.$emit('demo')
 
},
unbind(){
//this.$off('smytest')//解绑一个自定义事件
this.$off(['smytest','demo']) //解绑多个个自定义事件
//this.$off()// 解绑所有自定义事件
},
death(){
this.$destroy();// 销毁了当前student组件实例,销毁后所有的student 实例的自定义事件全都不奏效
},
 
 
},
 
 
 
 
}
</script>

<style scoped>
/* 组件的样式 */
.student{
background-color:cadetblue;
 
}

</style>