父组件:用import引入其他组件的当前.vue文件,被称为父组件。
子组件:被其他文件所引入,被称为子组件。
我在src/components下新建了个child.vue文件------子组件
src/views下新建了个parent.vue------父组件
父–>子
父向子传递数据通过props
parent.vue :
<template>
<div>
// 通过自定义组件名来child来引用
<v-child :msg="info"></v-child>
</div>
</template>
<script>
// 导入子组件
import child from '../components/child'
export default {
data(){
return{
info:"信息"
}
},
components: {
// 定义组件名
'v-child':child
},
};
</script>
child.vue :
<template>
<div>
{{msg}}
</div>
</template>
<script>
export default {
// props可以是对象形式,也可是数组形式(数组中的值要用引号包裹)
props:{
msg:{default:'cheng',type:String}
}
}
</script>
子–>父
子组件通过this.$emit(“event-name”,可选参)来触发事件
父组件通过@event-name="changeArea"来设置监听
parent.vue :
<template>
<div>
// 自定义世间名
<v-child :msg="info" @chang-status="changeArea"></v-child>
</div>
</template>
<script>
import child from '../components/child'
export default {
data(){
return{
info:"信息"
}
},
components: {
"v-child":child
},
// 自定义事件名
methods:{
changeArea(value){
this.info=value
}
}
};
</script>
child.vue :
<template>
<div>
<button @click="changeMsg">{{msg}}</button>
</div>
</template>
<script>
export default {
props:{
msg:{default:'cheng',type:String}
},
data(){
return{
// 通过data保存初始值
thisInFo:this.msg
}
},
methods:{
// 点击事件
changeMsg(){
this.$emit("chang-status","切换")
}
}
}
</script>