A
A
artloveyou2021-11-05 22:27:23
Vue.js
artloveyou, 2021-11-05 22:27:23

How, depending on the presence of a property in the parent component, add it to the child in data()?

There are three components: parent, child and third party (child of child).
The third party accepts the settings object, the child carries the main settings that do not change plus the parent ones. Sometimes the parent can pass uniqOption: 3, and sometimes uniqOption2: 4. How to correctly accept such properties in the child?
uniqOption: 3 and uniqOption2 are in the third party component, but they don't always need to be passed from the parent.

// parentComponent 1
<template>
  <childComponent :data="data" />
</template>
<script>
// дочерний компонент
export default {
  data() {
    return {
      data: {
        uniqOption: 3
      }
    }
  }
}
</script>

// parentComponent 2
<template>
  <childComponent :data="data" />
</template>
<script>
// дочерний компонент
export default {
  data() {
    return {
      data: {
        uniqOption: 3,
        uniqOption2: 4
      }
    }
  }
}
</script>

// childComponent
<template>
  <third-part-component :options="options" />
</template>
<script>
// дочерний компонент
export default {
  props: {
    data: Object,
  },
  data() {
    return {
      options: {
         foo: 1,
         bar: 2,

         // как сюда добавить при наличии в родительском компоненте свойство
         // uniqOption: 3 и uniqOption2: 4
         // но не так 
         // uniqOption: this.data.uniqOption
         // uniqOption2: this.data.uniqOption2
      }
    }
  }
}
</script>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aetae, 2021-11-05
@artloveyou

computed: {
  mergedOptions() {
    return {
      ...this.data,
      ...this.options
    }
  }
}

<third-part-component :options="mergedOptions" />
?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question