Subscribe on changes!

can not use defineProps in a usexxx function

avatar
May 8th 2022

Version

3.2.33

Reproduction link

sfc.vuejs.org/

Steps to reproduce

useModel.js:

import { computed, defineProps, defineEmits } from 'vue'

export default function (defaultValue = false) {
  const props = defineProps({
    modelValue: {
      type: [Boolean, String, Array, Object],
      default: defaultValue
    }
  })
  const emit = defineEmits(['update:modelValue'])
  const value = computed({
    get() {
      return props.modelValue
    },
    set(v) {
      emit('update:modelValue', v)
    }
  })
  return value
}

and i use it in the child.vue as:

<script setup>
import useModel from './useModel'
const visible = useModel(false)
</script>

<template>
  <div class="modal" v-show="visible"> </div>
</template>

then i import the child.vue in parent.vue:

<script setup>
  import Child from '../components/Child.vue'
  const visible = ref(false)
</script>

<template>
  <child v-model="visible" />
</template>

and it has problem at last:

runtime-core.esm-bundler.js:1085 Uncaught (in promise) TypeError: Cannot read properties of null (reading 'emitsOptions') ...

What is expected?

no problem to use the function useModel.js

What is actually happening?

have a wrong tip in console: runtime-core.esm-bundler.js:1085 Uncaught (in promise) TypeError: Cannot read properties of null (reading 'emitsOptions') ...

avatar
May 8th 2022

That's not supported. defineProps and defineEmits() are compiler hints that can only be processed within a script setup block.

you need to return the plain objects from your function (or export them separately) and then pass them to defineProps() and defineEmits() in the consuming component.

avatar
May 8th 2022

That's not supported. defineProps and defineEmits() are compiler hints that can only be processed within a script setup block.

you need to return the plain objects from your function (or export them separately) and then pass them to defineProps() and defineEmits() in the consuming component.

I think it so be support to use defineProps and defineEmits() not only within a script setup block. look at the options's way, we can use mixins like props, computed, methods, mounted and so on. why it is not support props, emits and just support methods, mounted at the setup way?

avatar
May 9th 2022

It's in the official documentation

avatar
May 9th 2022

这是不支持的。defineProps并且defineEmits()是只能在脚本设置块中处理的编译器提示。 您需要从函数中返回普通对象(或单独导出它们),然后将它们传递给消费组件defineProps()并在其中传递。defineEmits()

我认为它支持使用definePropsdefineEmits() 而不仅仅是在脚本设置块中。看options的方式,我们可以使用mixinsprops, computed, methods, mounted之类的。为什么它不支持props, emits ,只支持methods, mounted设置方式?

or, you can try getCurrentInstance api