Search code examples
javascripttypescriptvue.js

How to modify array of objects after that is created inside a watcher


I have a Vue 3 app that is using composition API and TypeScript. For a breadcrumb into the code of a component there is a watcher that will push the route name and path inside an array of objects after a switch is checking for the correct route to use. At the moment I need to remove the first two objects from the created object array inside the watchers, I've tried using a splice, but seems not working inside the watchers. Is it possible to modify an array of objects to remove elements from it if a condition is true and directly from inside the watchers?


Solution

  • I've tried using a splice, but seems not working inside the watchers

    It does work, but you have to use watch with deep: true.

    But I suggest not to modify the current value, but to rewrite it entirely.

    const breadcrumbs = ref([
      { label: 'Home', path: '/home' },
      { label: 'About', path: '/about' },
    ])
    
    watch(someRef, () => {
      breadbrumbs.value = [
         ...breadcrumbs.value,
        { label: 'New crumb', path: '/crumb-path' },
      ]
    })