父子组件传递参数
在 uni-app 中,自定义组件之间可以通过 props 和事件的方式进行参数传递。下面我将详细说明父子组件之间相互传递参数的方法:
- 父组件向子组件传递参数(使用 props):
- 在子组件的 vue 文件中,通过
props
字段定义需要接收的参数。- 在父组件使用子组件的地方,通过绑定属性的方式将数据传递给子组件。
子组件示例代码(Child.vue):
<template>
<div>
<h2>{{ title }}</h2>
<p>{{ content }}</p>
</div>
</template>
<script>
export default {
props: {
title: {
type: String,
required: true
},
content: {
type: String,
default: ''
}
}
}
</script>
父组件示例代码(Parent.vue):
<template>
<div>
<child-component :title="title" :content="content"></child-component>
</div>
</template>
<script>
import ChildComponent from '@/components/Child.vue';
export default {
components: {
ChildComponent
},
data() {
return {
title: '标题',
content: '内容'
}
}
}
</script>
- 子组件向父组件传递参数(使用事件):
- 在子组件中通过
$emit
方法触发一个自定义事件,并将需要传递的数据作为参数传入。- 在父组件中监听子组件触发的自定义事件,并在相应的方法中获取传递的参数。
子组件示例代码(Child.vue):
<template>
<button @click="handleClick">点击触发事件</button>
</template>
<script>
export default {
methods: {
handleClick() {
const data = '这是子组件传递的数据';
this.$emit('child-event', data);
}
}
}
</script>
父组件示例代码(Parent.vue):
<template>
<div>
<child-component @child-event="handleChildEvent"></child-component>
<p>接收子组件传递参数:{{ childData }}</p>
</div>
</template>
<script>
import ChildComponent from '@/components/Child.vue';
export default {
components: {
ChildComponent
},
data() {
return {
childData: ''
}
},
methods: {
handleChildEvent(data) {
this.childData = data;
}
}
}
</script>
通过上述方法,父组件和子组件就可以相互传递参数。父组件通过 props 将数据传递给子组件,子组件通过事件将数据传递给父组件,实现了双向的参数传递。
默认插槽
在 uni-app 中,插槽(slot)是一种用于在组件内部插入内容的机制。通过插槽,我们可以将外部传入的内容动态地插入到组件的指定位置。uni-app 支持两种类型的插槽:默认插槽和具名插槽。
- 默认插槽:
默认插槽是最基本的插槽类型,它允许在组件中插入任意内容。在组件的模板中使用
<slot></slot>
标签来表示默认插槽的位置。组件示例代码(Child.vue):
<template>
<div>
<h2>我是子组件</h2>
<slot></slot>
</div>
</template>
<script>
export default {
}
</script>
父组件示例代码(Parent.vue):
template>
<div>
<child-component>
<p>这是插入到子组件的内容</p>
</child-component>
</div>
</template>
<script>
import ChildComponent from '@/components/Child.vue';
export default {
components: {
ChildComponent
}
}
</script>
在上述示例中,我们在父组件中使用了
<child-component>
标签,并在其中插入了一个<p>
标签。这个<p>
标签就会被动态地插入到子组件的默认插槽位置。
具名插槽
具名插槽允许我们在组件中定义多个插槽,并可以根据需要将内容插入到指定的插槽中。在组件的模板中使用
<slot name="插槽名称"></slot>
标签来表示具名插槽的位置。组件示例代码(Child.vue):
<template>
<div>
<h2>我是子组件</h2>
<slot name="content"></slot>
<slot name="footer"></slot>
</div>
</template>
<script>
export default {
}
</script>
父组件示例代码(Parent.vue):
<template>
<div>
<child-component>
<template v-slot:content>
<p>这是插入到内容插槽的内容</p>
</template>
<template v-slot:footer>
<button>提交</button>
</template>
</child-component>
</div>
</template>
<script>
import ChildComponent from '@/components/Child.vue';
export default {
components: {
ChildComponent
}
}
</script>
在上述示例中,我们在子组件中定义了两个具名插槽:
content
和footer
。在父组件中,我们使用了<template>
标签,并通过v-slot
指令来选择需要插入的具名插槽。在v-slot
中,我们使用:name
的形式指定要插入的插槽名称。通过使用插槽,我们可以在组件中灵活地插入外部的内容,实现更高度的组件复用和定制。默认插槽和具名插槽的使用方式略有差异,但都能满足不同场景下的需求。