Having recently delved into Vue, I am facing a challenge that has left me scratching my head after consulting the documentation:
- I am struggling to pass an arbitrarily named variable as a prop to a component instance.
As per my understanding, props serve as a means to transmit data to a component and according to the official website:
Passing Data to Child Components with Props: Props are custom attributes you can register on a component. When a value is passed to a prop attribute, it becomes a property on that component instance.
Given the option for props to be required
, it appears that we can construct components with the assumption that certain data will always be present, possibly adhering to specific criteria if the validator option is specified.
My objective is to define a function or object externally from Vue, perhaps within the application itself, and then pass this function or object to my Vue instance.
The issue arises when attempting to bind a function or object with a different name than the prop in multiple instances of the Vue component, as using identical names is less than ideal.
If I adhere to the advice provided by Vue and align the object/function name with the prop name, a warning surfaces stating that the data is not defined within Vue and advises on ensuring its reactivity by referring to: https://v2.vuejs.org/v2/guide/components-props.html
However, this resource does not offer a clear solution to address the concern,
Aside from relocating the prop to the data level.
Although feasible (still prompting the same warning), this approach somewhat undermines the purpose of employing props based on my current Vue comprehension.
Complications further ensue when dealing with anonymous Vue instances.
For example:
<script>
export default {
props: {
// records: {
// default: function(){return{}},
// type: Object
// }
},
data: function() {
return {
records: {} // even defining an empty value in data is necessary for reactivity
}
},
computed: {
fields: function() {
},
keys: function() {
return Object.keys(this.records)
}
},
methods: {
}
}
</script>
Trying to employ the above as a component and assigning records to
var myRecords = {"a": {}}
results in failure:
<my-comp :records="myRecords"/>
So how do I effectively navigate around this dilemma? Where should I declare my data then? and how can I manage naming when handling multiple instances?
A more elaborate example can be found in a similar inquiry:
Vue2: passing function as prop triggers warning that prop is already set