0

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 :)

1 Answer 1

2

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(...).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.