0

I'm using recursive components in vue.js. Every component has an array where one value is passed from the parent component as a prop. How do I have to create the array to properly include the value/prop?

Here are the details with simplified (untested) code to show the theoretical problem (I know that this example causes infinite recursion :-):

My-component.vue

<template>
  {{my_array}}
  <my-component :my_counter="my_array.counter">
</template>

<script>
module.exports = {
  props: ['my_counter'],
  name: 'my-component', 
  data: function () {
    return {
      new_counter: this.my_counter+1,
      my_array: [name: "static name", counter: this.new_counter]
    }
  },
 }
</script>

Though new_counter is properly passed as my_counter prop to the child component, the my_array.counter is not properly updated with the new value.

When I pass new_counter as my_counter property directly (without using the array). It works.

I guess I need to use some kind of reactive data. However, I couldn't find a solution with computed properties, methods etc... How can I make my_array updated by the the passed prop?

What is your recommendation to solve this problem?

2 Answers 2

1

The issue with your code is that my_array initialized once used props but then it's not updated. You have to add a watcher like that:

watch: {
  my_counter(value) {
    this.my_array = {
      ...this.my_array,
      counter: value
    }
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

I'm quite new to Vue.js and I've had similar issues with it and Nuxt.js. Although, I've got one example that might help you. Did you try anything like this?

<template>
  {{my_array}}
  <my-component :my_counter="compA()">
</template>

<script>
module.exports = {
  props: ['my_counter'],
  name: 'my-component', 
  computed: {
    compA() {
       const my_counter = this.my_counter ? this.my_counter : []; 
       let my_array = [name: "static name", counter: my_counter];
       return my_array;
    }
  }
 }
</script>

1 Comment

The problem persists: The variable my_counter is "undefined" at this point. However, when displaing the property, the variable my:counter is properly shown.

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.