学习Vue3 第十一章(父子组件传参)

56 阅读1分钟

父传子

父组件通过v-bind绑定一个数据,然后子组件通过defineProps接受传过来的值

<template>
  <div>字符串:{{ text }}</div>
  <div>数组:{{ arr }}</div>
</template>
<script setup>
const props = defineProps({
  text: {
    type: String,
    // required: true,  必传
    default: 'Default text', // 默认值
  },
  arr: {
    type: Array,
    default: () => [3, 3], // 要返回一个函数
  },
})

console.log(props.text, 'props')
</script>
<style scoped lang="scss"></style>

子传父

我们在子组件绑定了click事件,然后通过defineEmits注册了一个自定义事件,触发emit去调用这个自定义事件,然后传递参数

父组件

<template>
  <div>
    <Card @change="change" />
  </div>
</template>

<script setup>
import { ref } from 'vue'
import Card from './components/Card.vue'
const text = ref('yoga')

const change = v => {
  console.log(v)
}
</script>

<style scoped></style>

子组件

<template>
  <div>字符串:{{ text }}</div>
  <div>数组:{{ arr }}</div>
  <button @click="btnClick">给父传递参数</button>
</template>
<script setup>
const props = defineProps({
  text: {
    type: String,
    // required: true,  必传
    default: 'Default text', // 默认值
  },
  arr: {
    type: Array,
    default: () => [3, 3], // 要返回一个函数
  },
})

const emits = defineEmits(['change'])

const btnClick = () => {
  emits('change', '子组件传递的参数')
}

console.log(props.text, 'props')
</script>
<style scoped lang="scss"></style>

根据子组件实例获取子组件暴露出来的方法给父组件

父组件

<template>
  <div>
    <Card @change="change" ref="childRef" />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import Card from './components/Card.vue'
const text = ref('yoga')
const childRef = ref('') // 获取子组件的实例
onMounted(() => {
  console.log(childRef.value, '===')
})

const change = v => {
  console.log(v)
}
</script>

子组件

defineExpose({
  //  暴露给父组件
  name: 'yoga',
})