父子组件进行传参
父传子
原理:父控制子,通过子组件的props属性,抛出子组件自定义标签属性,来接收父组件的操作状态。
// 父
<template>
<div>
<child-module :content="content"/>
</div>
</template>
<script>
import ChildModule from '@/components/ChildModule.vue'
export default {
name: 'FatherModule',
components: {
ChildModule
},
data() {
return {
content: "text"
}
}
}
</script>
// 子
<template>
<div>
<div>{{ content }}</div>
</div>
</template>
<script>
export default {
name: 'ChildModule',
props: {
content: {
// 定义接收的类型 还可以定义多种类型 [string,Undefined,Number]// 如果required为true,尽量type允许undefined类型,因为传递过来的参数是异步的。或者设置默认值
type: String,
// 定义是否必须传
required: true,
// 定义默认值
default: '暂⽆'
}
}
}
</script>
子传父
原理:子控制父,子组件绑定自定义事件,来处理父组件的方法函数,通过.$emit(‘自定义事件’,[参数]) 来触发属于自己的自定义事件。
// 父
<template>
<div>
<child-module
ref="childModuleRef"
:content="content"
@getData="getData"/>
<div>{{ childValue }}</div>
</div>
</template>
<script>
import ChildModule from '@/components/ChildModule.vue'
export default {
name: 'FatherModule',
components: {
ChildModule
},
data() {
return {
content: "text",
childValue: ''
}
},
methods: {
// childrenData就是⼦组件传递过来的参数
getData(childrenData) {
console.log(childrenData)
this.childValue = childrenData
}
}
}
</script>
// 子
<template>
<div>
<div>{{ content }}</div>
<button @click="onClick">点击向⽗组件传参</button>
</div>
</template>
<script>
export default {
name: 'ChildModule',
props: {
content: {
type: String,
required: true,
default: '暂⽆'
},
},
data() {
return {
num: 1
}
},
methods: {
onClick() {
this.$emit("getData",this.num)
}
}
}
</script>