defineProps、defineEmits

父组件:

<child
      ref="child"
      @get="get"
/>

<script setup>
import { ref } from 'vue'

const info = reactive({
  name: 'jjj'
})

const child = ref(null)

function get() {
	console.log(child.value, 'get') //为null
}
</script>

子组件:

<template>
  <div>
    <p>children: {{ nfo.name }}</p>
    <el-button @click="showChildren"> showChildren</el-button>
  </div>
</template>

<script setup>
const props = defineProps({  //获取父组件值
  info: {
    type: Object,
    required: true,
    default: () => ({})
  }
})

const emit = defineEmits(['get'])

function showChildren() {
	emit('get', 'showChildren')  // 执行get方法
  	console.log('this is children')
}
</script>

此时打印出来发现,children.value为null

重名问题

父组件:

<child
      ref="childRef" // ref不能与组件重名,不然获取的value为null
      @get="get"
/>

<script setup>
import { ref } from 'vue'

const info = reactive({
  name: 'jjj'
})

const childRef = ref(null)

function get() {
	console.log(childRef.value, 'get') //没有showChildren方法
}
</script>

此时打印出来发现,children.value有值了,但是里面没有showChildren

defineExpose

父组件:

<child
      ref="childRef"
      @get="get"
/>

<script setup>
import { ref } from 'vue'

const info = reactive({
  name: 'jjj'
})

const childRef = ref(null)

function get() {
	console.log(childRef.value, 'get') //有showChildren方法
}
</script>

子组件:

<template>
  <div>
    <p>children: {{ nfo.name }}</p>
    <el-button @click="showChildren"> showChildren</el-button>
  </div>
</template>

<script setup>
const props = defineProps({  //获取父组件值
  info: {
    type: Object,
    required: true,
    default: () => ({})
  }
})

const emit = defineEmits(['get'])

function showChildren() {
	emit('get', 'showChildren')  // 执行get方法
  	console.log('this is children')
}

defineExpose({  //加入以后抛出showChildren,父组件可以获取
  showChildren
})
</script>

此时打印出来发现,children.value里面有showChildren

注意:只有 < script setup >的时候才需要使用defineExpose抛出方法,使用setup()函数则不用。

Logo

前往低代码交流专区

更多推荐