vue--day45---组件的自定义指令

1.App.vaule

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

<!--通过父组件给子组件绑定一个自定义事件实现 子给父传数据 第二种写法 使用ref-->
<Student ref="student"></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"
}
 
},

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


//receiveStuedntName(studentName,...a){ 接收多个参数,第一个参数 后面的几个参数全部封装为数组
receiveStuedntName(studentName){
console.log("app组件收到了学生的名字信息",studentName);
}
},
mounted(){
//this.$refs.student.$on('smytest',this.receiveStuedntName)

setTimeout(()=>{

 
this.$refs.student.$on('smytest',this.receiveStuedntName)
//触发一次
// this.$refs.student.$once('smytest',this.receiveStuedntName)

})
}
 
2. School.vue
<template>
<!-- 组件的介绍 -->
<div class="school">

<h2>学校名称{{name}}</h2>
<h2>学校地址{{address}}</h2>
<button @click="sendSchoolName"> 点我将学校名称送给APP</button>

</div>
</template>



<script>


export default {
name:"School",
props:['receiveSchoolName'],
data() {
return {
name: "洛阳理工",
address: "洛阳"
};
},

methods: {
sendSchoolName() {
this.receiveSchoolName(this.name)
},
},
 
}

 
</script>


<style scoped>
/* 组件的样式 */
.school{
background-color:orange;
margin-top: 20px;
}

</style>
3. Student.vue
 
<template>
<div class="student">
 
<h2>学生姓名{{name}}</h2>
<h2>学生性别{{sex}}</h2>
 
<button @click="sendStudentName">点我将学生名字传递给App</button>
 
</div>
</template>


<script>


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

methods: {
sendStudentName(){
// 触发Student 组件实例对象上的 smytest 事件
// 如果参数过多 1.可以把数据封装为对象
// 2. this.$emit('smytest',this.name,99999,8888,4444)
this.$emit('smytest',this.name,99999)
}
 
},
 
 
 
 
}
</script>

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

</style>




 
}
</script>

<style scoped>

</style>



 
 
 
posted @ 2023-07-26 01:24  雪落无痕1  阅读(13)  评论(0编辑  收藏  举报