CookieThief
CookieThief

Reputation: 166

Vue3 / Nuxt3 - how to use props directly in setup

Can you please help me fix this error : Getting a value from the props in root scope of <script setup> will cause the value to lose reactivity.(vue/no-setup-props-destructure)

I'm using :

This is a sample code which illustrate the problem :

<script lang="ts" setup>
  const props = defineProps<{ fruit: string }>()
  const fruitColor = ref<FruitColor>(getColor(props.fruit))
</script>

This is my .eslintrc.js, it may help

module.exports = {
  root: true,
  env: {
    browser: true,
    node: true
  },
  extends: ['@nuxtjs/eslint-config-typescript', 'plugin:nuxt/recommended', 'plugin:vitest/recommended', 'prettier'],
  rules: {
    'vue/script-indent': ['error', 2, { baseIndent: 1 }],
    'vue/max-len': ['error', { code: 120 }],
    'vue/component-name-in-template-casing': [
      'error',
      'kebab-case',
      {
        registeredComponentsOnly: true,
        ignores: []
      }
    ],
    'comma-dangle': ['error', 'never'],
  }
}

Upvotes: 0

Views: 1385

Answers (2)

CookieThief
CookieThief

Reputation: 166

I forgot to go back in order to answer after I found the solution. It's in the doc : https://vuejs.org/api/reactivity-utilities toRef(props.fruit) or const {fruit} = toRefs(props) to transform all.

// creates read and write access without modifying original props.fruit
toRef(props.fruit)

// creates a readonly ref that calls the getter on .value access
toRef(() => props.foo)

Upvotes: 0

VasanthThoraliKumaran
VasanthThoraliKumaran

Reputation: 71

Consider using a computed property instead of a ref. Computed properties inherently monitors their reactive dependencies, so any changes in props.fruit will effectively trigger reactivity.

Code Changes:

<script lang="ts" setup>
  const props = defineProps<{ fruit: string }>()
  const fruitColor = computed<FruitColor>(() => getColor(props.fruit));  
</script>

Upvotes: 0

Related Questions