Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Update array properties dynamically in Vue 3 composition API when route param changes

My component (Vue 3 with composition API + script setup) has a property linkList. This shall be updated whenever the route param id changes.

Example

When calling this component on /user/1, then linkList shall look like this:

{id: 1, name: 'foo'},
{id: 1, name: 'bar'}

This is my current code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<script setup>

const route = useRoute();
const idRouteParam = computed(() => route.params.id);

const linkList = [
{
  id: idRouteParam,
  name: 'foo',
},
{
  id: idRouteParam,
  name: 'bar',
}
];

watch(
  idRouteParam,
  () => {
    console.log(idRouteParam);
  },
  { immediate: true },
);

</script>

The problem is: linkList is only updated after the page is refreshed, i.e. the component is re-created. When idRouteParam changes (example: /user/2), then linkList has the original values from user 1. I thought that I could update it in the watcher but I guess I’m missing some piece of the puzzle.

>Solution :

The linkList should be also defined as a computed property :

const linkList = computed(()=>[
{
  id: idRouteParam,
  name: 'foo',
},
{
  id: idRouteParam,
  name: 'bar',
}
]);

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading