1,父传子
这是父组件
重点:
父组件引用子组件,在子组件里面使用v-bind绑定,那么传过去的text就是就是data里面的值
如果不适用v-bind,那传过去的就是msg="text"的text这个字符串,不会关联data数据
<template>
<div id="app">
父组件
<hr />
<Course :msg="text"/>
</div>
</template>
<script>
import Course from './components/Course.vue'
export default {
name: 'App',
data(){
return{
text:'我是属于父组件的值text',
}
},
components: {
Course,
},
}
</script>
<style>
</style>
这是子组件,使用props进行接收msg进行调用
重点:如果要限制传值的类型,必要性,默认值,定义默认值的时候,把必要性去掉,参考方式如下
props:{
xd:{
type: string,
//required: true,
default: '我是默认值'
}
<template>
<div>
子组件
{{msg}}
</div>
</template>
<script>
export default {
data(){
return{}
},
props:['msg']
}
</script>
运行:使用v-bind
运行:不使用v-bind
默认传过来的值是不可以直接更改的,但是可以将传过来的值当成一个data变量的内容,然后去改变这个变量
<template>
<div>
子组件
{{happy}}
<button @click="mag()">改变msg</button>
</div>
</template>
<script>
export default {
data(){
return{
happy:this.msg,
}
},
props:['msg'],
methods:{
mag(){
this.happy="我是一个happy"
}
}
}
</script>
2,子传父
方法1-------------------------------------
父组件通过props传给子组件时间回调传值
通过父组件声明一个方法,传递给子组件,然后子组件通过props接收方法,给方法传入一个变量,父组件通过参数i获取到值,将值给到text,然后进行渲染
<template>
<div id="app">
父组件
{{text}}
<hr>
<Course :item="transmit" />
</div>
</template>
<script>
import Course from './components/Course.vue'
export default {
name: 'App',
data(){
return{
text:'',
}
},
components: {
Course,
},
methods:{
transmit(i){
this.text=i;
}
}
}
</script>
<style>
</style>
子组件
<template>
<div>
子组件
</div>
</template>
<script>
export default {
data(){
return{
happy:"我是一个子组件的值",
}
},
props:['msg','item'],
mounted(){
this.item(this.happy);
}
}
</script>
运行一下,子组件的值就给到父组件了
方法2-------------------------------------
通过父组件定义一个事件item,使用v-on绑定到子组件,子组件通过$emit接收这个事件,并传入参数,父组件通过item将参数传给text,进行打印显示
<template>
<div id="app">
父组件
{{text}}
<hr>
<Course @item="transmit" />
</div>
</template>
<script>
import Course from './components/Course.vue'
export default {
name: 'App',
data(){
return{
text:'',
}
},
components: {
Course,
},
methods:{
transmit(i){
this.text=i;
}
}
}
</script>
<style>
</style>
子组件
<template>
<div>
子组件
</div>
</template>
<script>
export default {
data(){
return{
happy:"我是一个子组件的值",
}
},
mounted(){
this.$emit("item",this.happy)
}
}
</script>
方法3-------------------------------------
重点:父组件使用ref进行监听,mounted创建一个自定义事件item,使用
o
n
进
行
监
听
,
子
组
件
使
用
on进行监听,子组件使用
on进行监听,子组件使用emit去监听item事件,并传入参数,父组件通过事件接收的参数给到text,进行打印显示
<template>
<div id="app">
父组件
{{text}}
<hr>
<Course ref="child" />
</div>
</template>
<script>
import Course from './components/Course.vue'
export default {
name: 'App',
data(){
return{
text:'',
}
},
components: {
Course,
},
mounted(){
this.$refs.child.$on("item",(i)=>{
this.text = i
})
}
}
</script>
<style>
</style>
子组件
<template>
<div>
子组件
<button @click="clickItem">点击传过去</button>
</div>
</template>
<script>
export default {
data(){
return{
happy:"我是一个子组件的值",
}
},
methods:{
clickItem(){
this.$emit("item",this.happy)
}
}
}
</script>
解绑的话就是使用$off,另外一般解绑都在beforeDestroy的生命周期函数里