Home > Mobile >  Vue 3 ref array doesnt update values
Vue 3 ref array doesnt update values

Time:08-17

Description

I'm new to Vue 3 and the composition API. When i try to delete values in an array declared with ref, values do not delete.

Code preview

Here is my code

<script setup lang="ts">
import { IPartnerCategory, IPartners } from '~~/shared/types'

const selectedPartnershipCategories = ref([])
const props = withDefaults(
  defineProps<{
    partnershipCategories?: IPartnerCategory[]
    partnerships?: IPartners[]
    freelancer?: boolean
  }>(),
  {
    partnershipCategories: () => [],
    partnerships: () => [],
    freelancer: false,
  }
)

const emit =
  defineEmits<{
    (e: 'update:value', partnership: IPartnerCategory): void
    (e: 'update:selected', select: boolean): void
  }>()

const updateSelectedPartnership = (partnershipId: string, categorySelected: boolean) => {
  if (categorySelected && !selectedPartnershipCategories.value.includes(partnershipId)) {
    return selectedPartnershipCategories.value.push(partnershipId)
  }
  if (!categorySelected && selectedPartnershipCategories.value.includes(partnershipId)) {
    const clearedArray = selectedPartnershipCategories.value.filter((i) => {
      return i !== partnershipId
    })
    console.log(clearedArray)
  }
}

const select = (event) => {
  updateSelectedPartnership(event.fieldId, event.isSelected)
}
</script>

  • My array is declared as selectedPartnershipCategories
  • I've a function named updateSelectedPartnesh, called everytime when i update a value in the selectedPartnership array
  • When i log clearedArray values are only pushed but not deleted.

Thanks in advance for your help :)

CodePudding user response:

This is because filter creates a shallow copy and does not modify the original array.

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(word => word.length > 6);

console.log(result);
console.log(words);

If you want to modify selectedPartnership, you should use splice or another method, or simply selectedPartnership = selectedPartnership.filter(...).

  • Related