通信原创
# 传参 Props
在子组件中使用 defineProps
件下文。
# 默认值
setup 中设置!!!
// 定义 Props 类型
type Props = {
title: string,
data?: number[], // ?: 为可选参数
children?: Props[] | [] // 可以为本身的 Props 类型 或 空数组,用于树形结构
}
// 为Props 设置默认值
withDefaults(defineProps<Props>(), { // defineProps 在 setup 中无需引入,可直接使用
title: '我是子组件',
data: () => [] // data 是数组或对象时不能直接 [] {} 而要使用方法传递
})
# 事件
<template>
<view>
<view>
{{ title }}
</view>
<view vi-if="data">
{{data}}
</view>
<view>
<buttoun @click="clickTap">点击事件</buttoun>
</view>
<view>
<buttoun @click="fasong">发送事件</buttoun>
</view>
</view>
</template>
<script setup lang='ts'>
import { reactive } from 'vue'
// 定义 Props 类型
type Props = {
title: string,
data?: number[] // ?: 为可选参数
}
// reactive 用于重新复制,是响应式操作
const list = reactive<number[]>([1, 2, 3])
defineProps<Props>() // defineProps 在 setup 中无需引入,可直接使用
const emit = defineEmits(['dianji', 'fasong']) // defineEmits 在 setup 中无需引入,可直接使用
// dianji fasong 是为事件命名,可以声明多个,然后在父组件中使用 @dianji @fasong 来实现事件
const clickTap = () => {
emit('dianji', list) // 第一个参数是事件名称,第二个以后的参数为相关数据
}
const fasong = () => {
emit('fasong', list, false) // 第一个参数是事件名称,第二个以后的参数为相关数据
}
</script>
# 获取子组件实例
在父组件中,为子组件定义 ref
<template>
<view class="content">
<Children ref="child" title="父组件调用子组件了" @dianji="getList" @fasong="getLists"></Children>
<view></view>
</view>
</template>
<script setup lang="ts">
import Children from '../../component/children'
import { storeToRefs } from 'pinia'
import { reactive, ref, toRef } from 'vue'
const list = reactive<number[]>([1, 2, 3])
const child = ref(null) // 此处命名必须与 ref 一致
const getList = (list:number[]) => {
console.log(list, '子组件传过来的数据')
}
const getLists = (list:number[]) => {
console.log(list, '发送子组件传过来的数据')
console.log(child.value) // 获取子组件实例
console.log(child.value.list) // 获取实例中的数据
}
</script>
默认情况下,父组件中获取到的子组件实例没有任何内容,需要在子组件中使用
// 子组件
<template>
<view>
<view>
{{ title }}
</view>
<view vi-if="data">
{{data}}
</view>
<view>
<buttoun @click="clickTap">点击事件</buttoun>
</view>
<view>
<buttoun @click="fasong">发送事件</buttoun>
</view>
</view>
</template>
<script setup lang='ts'>
import { reactive, ref } from 'vue'
// 定义 Props 类型
type Props = {
title: string,
data?: number[] // ?: 为可选参数
}
// reactive 用于重新复制,是响应式操作
const list = reactive<number[]>([1, 2, 3, 4, 5])
const flag = ref(false)
defineProps<Props>() // defineProps 在 setup 中无需引入,可直接使用
const emit = defineEmits(['dianji', 'fasong']) // defineEmits 在 setup 中无需引入,可直接使用
// dianji fasong 是为事件命名,可以声明多个,然后在父组件中使用 @dianji @fasong 来实现事件
const clickTap = () => {
emit('dianji', list) // 第一个参数是事件名称,第二个以后的参数为相关数据
}
const fasong = () => {
emit('fasong', list, false) // 第一个参数是事件名称,第二个以后的参数为相关数据
}
// defineExpose 在 setup 中无需引入,可直接使用,将该组件的相关数据暴露出去
defineExpose({
// 需要暴露出去的数据、方法等,可以是多个
list,
flag
})
</script>
<style lang='scss'>
</style>
上次更新: 2022/08/23, 18:12:45