Rade Iliev
Rade Iliev

Reputation: 229

Vue 3, get props in setup

I have some problems getting props value (that is array actually) into my composition api (setup). So I have component that is called DropDown, and I'm passing it some array of objects, and I need to do something like this:

export default {
  emits: ['update:modelValue'],
  props: {
    items: {
      type: Array,
      // required: true
    },
    modelValue: {
      type: [String, Number, Boolean],
      required: true
    }
  },

  setup({modelValue, props} : any, {emit} : any ) {
    let is_active = ref(false);
    let selected = ref({
        label: props.items[0].label,
        icon: props.items[0].icon,
        class: props.items[0].class
    });

as you see I have let selected that must have first object of items array, but it's not working. I'm listing items without problem on my template, but on setup I can't. Any ideas how to fix it?

btw: Best practise is to use like let selected = reactive(props.items[0]) but, it's not working like this as well.

Upvotes: 2

Views: 7580

Answers (1)

tony19
tony19

Reputation: 138276

The problem is your setup() is destructuring a props property from the props argument.

           props argument
      -------------------------
setup({modelValue, props} : any, {emit} : any) {
                   ^^^^^ ❌ props.props does not exist

However, destructuring the props argument should be avoided (as warned in the docs) because it removes the reactivity of the destructured prop.

The fix is to remove the destructuring from the props argument. Also, you can enable type inference for the props and context arguments by using the defineComponent() helper function from vue to define the component:

import { defineComponent, ref } from 'vue'

export default defineComponent({
  setup(props, context) {
    let selected = ref({
      label: props.items[0].label,
      icon: props.items[0].icon,
      class: props.items[0].class
    });

    //...
  }
})

Upvotes: 4

Related Questions