props父传子
子传父的两种方式
props父传子
使用props传输的时候还可以进行时数据的限制
// App文件
<template>
<div>
<Student name="李四" sex="女" :age="18"/>
</div>
</template>
<script>
import Student from './components/Student'
export default {
name:'App',
components:{Student}
}
</script>
// Student文件
<template>
<div>
<h1>{{msg}}</h1>
<h2>学生姓名:{{name}}</h2>
<h2>学生性别:{{sex}}</h2>
<h2>学生年龄:{{myAge+1}}</h2>
<button @click="updateAge">尝试修改收到的年龄</button>
</div>
</template>
<script>
export default {
name:'Student',
data() {
console.log(this)
return {
msg:'我是一个尚硅谷的学生',
myAge:this.age
}
},
methods: {
updateAge(){
this.myAge++
}
},
//简单声明接收
// props:['name','age','sex']
//接收的同时对数据进行类型限制
/* props:{
name:String,
age:Number,
sex:String
} */
//接收的同时对数据:进行类型限制+默认值的指定+必要性的限制
props:{
name:{
type:String, //name的类型是字符串
required:true, //name是必要的
},
age:{
type:Number,
default:99 //默认值
},
sex:{
type:String,
required:true
}
}
}
</script>
子传父
Student.vue
<button @click="sendStudentlName">把学生名给App</button>
sendStudentlName(){
//触发Student组件实例身上的dome事件
this.$emit('dome',小周,666,888,900)
},
unbind(){
this.$off('dome') //解绑一个自定义事件
this.$off(['dome','demo2']) //解绑多个自定义事件
this.$off() //解绑所有的自定义事件
},
death(){
this.$destroy() //销毁了当前Student组件的实例,销毁后所有Student实例的自定义事件全都不奏效。
}
APP.vue
第一种
<!-- 通过父组件给子组件绑定一个自定义事件实现:子给父传递数据(第一种写法,使用@或v-on) -->
<Student @dome="getStudentName"/>
getStudentName(name,...params){
console.log('App收到了学生名:',name,params) //小周,[666,888,900]
}
第二种 灵活一点,可以添加更多操作,例如一个定时3s后在执行
<!-- 通过父组件给子组件绑定一个自定义事件实现:子给父传递数据(第二种写法,使用ref) -->
<Student ref="student" @click.native="show"/>
setTimeout(()=>{
this.$refs.student.on('dome',this.getStudentName)
},3000)
当使用组件子传父时候,直接使用@click="show",在vue中不会是点击事件,他把click当自定义事件去执行了
使用@click.native="show",转换一下,就可以直接使用了