[Vuejs]-Add properties to Vue component programatically

0👍

If you did not register the props inside your component x like

//x.vue
<script>
  export default {
    props : ['a']
  }
</script>

then the component wouldn’t know anything about props you pass to it. Props you pass to the component, but did not register, will be undefined.

However, it is not a problem to pass a complete object as prop to the component, like

/* 
   const obj = {
     a : 1,
     b : 2,
     c : 3
   }
*/

<x :dynprop="obj" />
<script>
  export default {
    props : ['dynprop'],
    mounted() {
      console.log(dynprop.a);
      
      // 1
    }
  }
</script>

Please see Passing Object as Props in the official Vue Docs : https://v2.vuejs.org/v2/guide/components-props.html#Passing-the-Properties-of-an-Object

This will probably your best option since

Vue does not allow dynamically adding new root-level reactive properties to an already created instance.

0👍

Please refer: https://v2.vuejs.org/v2/guide/reactivity.html#For-Objects. You can’t dynamically add any property Since Vue performs the getter/setter conversion process during instance initialization, a property must be present in the data object in order for Vue to convert it and make it reactive

Leave a comment