Vue3中父子组件传值方式,父组件调用子组件属性和函数

父组件传值给子组件和vue2类似,使用v-bind或者 :绑定属性,然后在子组件里面,使用defineProps实现接收。

子组件向父组件传值,需要先在子组件里面定义emit,然后发送消息传参。

父组件想调用子组件的属性的时候,需要在子组件里面使用defineExpose暴露出属性或者方法。

子组件代码:

<template>
  <div style="border: 1px solid red; margin: 10px;">
    <h2>子组件标题:{
   
   { title }}</h2>
    <div>
      <button @click="getTitle" >点击获取标题</button>
      <button @click="sendMsg">向父组件传值</button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onBeforeUnmount, onUnmounted } from 'vue'
// 父子组件传值
const props = defineProps({
  title: {
    type: String,
    default: '默认标题'
  }
})

// 子组件向父组件传值
const emit = defineEmits(["sendMsg"])
const sendMsg = ()=>{
  emit("sendMsg", "参数1", "参数2")
}

// 点击获取标题
const getTitle = ()=>{
  console.log("得到的标题是:", props.title);
  
}

// 组件销毁之前
onBeforeUnmount(() => {
  console.log('组件销毁之前')
})

// 组件销毁之后
onUnmounted(() => {
  console.log('组件销毁之后')
})



defineExpose({
  getTitle,
  name:"子组件暴露的属性"
})
</script>

<style scoped></style>

父组件代码:

<template>
  <div style="border: 1px solid orange">
    <h2>Vue3的生命周期</h2>
    <div>
      <button @click="updateContent">点击更改组件内容</button>
      <button @click="show">创建和销毁组件</button>
      <div ref="demo">{
   
   { content }}</div>
      <button @click="runSun">执行子组件函数</button>
      <AboutMe ref="aboutMe" v-if="display" @send-msg="receive"></AboutMe>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onBeforeMount, onMounted, onBeforeUpdate, onUpdated } from 'vue'
// import AboutMe from './views/AboutMe.vue'
import AboutMe from './views/AboutMe.vue'

console.log('setup语法糖模式中,可以直接在这里当做created函数使用')

const demo = ref<HTMLDivElement>()

const content = ref<string>('这是内容:div内容')

const display = ref<boolean>(true)

// 获取子组件实例
const aboutMe = ref()

const runSun = () => {
  aboutMe.value.getTitle()
  console.log('获取子组件暴露的属性:', aboutMe.value.name)
}

const receive = (m1, m2) => {
  console.log('父组件接收到子组件传递过来的参数:', m1, m2)
}

const updateContent = () => {
  content.value = 'div组价内容更新'
}

const show = () => {
  display.value = !display.value
}

// 页面渲染之前
onBeforeMount(() => {
  console.log('渲染之前', demo)
})

// 页面渲染之后
onMounted(() => {
  console.log('渲染之后', demo)
})

// 组件更新之前
onBeforeUpdate(() => {
  console.log('组件更新之前', demo)
})

// 组件更新之后
onUpdated(() => {
  console.log('组件更新之后', demo)
})
</script>

<style scoped></style>

实现的效果: 

 

猜你喜欢

转载自blog.csdn.net/weixin_44786530/article/details/130722486