Implementing dynamic props in Vue2 component by passing arbitrary named variables

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

Answer №1

My intention is to create a function or object outside of Vue, perhaps in an application, and then pass this function or object to my Vue instance.

Providing a concrete answer is challenging without knowing the specific structure of your code. Are you utilizing Webpack? Working with single-file components (.vue)? If so, there may be no need to rely on global variables as described in your question.

In a Vue application, it's recommended to have a single root Vue instance created using new Vue(...). Each component should be rendered within the template of the root component, subsequent templates, and so forth.

Consider the following template:

<my-comp :records="myRecords"/>

The property myRecords should be defined within the Vue component instance containing the above template. It can be declared in the data block, as a computed property, or as a prop.

Here's a brief example:

<div id="app">
  <my-comp :records="myRecords"></my-comp>
</div>
// Fetch records and store them in a global variable
var records = ...

// Create the root Vue instance
new Vue({
  el: '#app',
  data: {
    // The records array must be stored in the Vue component like this
    // for it to be accessible within the template.
    // Data transformation can also be applied if needed.
    myRecords: records.filter(r => r.name.startsWith('Bob'))
    // ^        ^
    // |        |
    // |        +--- reference to the global variable
    // |
    // +---- property name on the component instance
  }
})

Note that the MyComp component doesn't directly interact with the global variable records; instead, it receives its input through the records prop.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Attempting to determine income in JavaScript with the inclusion of two distinct rates

Trying to come up with a salary calculation for different rates within the same timeframe is proving to be quite challenging. For instance, between 10:00-15:00 the rate is $20 per hour and from 15:00 onwards it drops to $15 per hour. Check out the entire ...

Prevent rapid event triggers with a jQuery slider

I am currently working with an event function in JavaScript that involves a slider and a tooltip element. Here is the code snippet: //Hide the Tooltip initially tooltip.hide(); //Initialize the Slider slider.slider({ ...

In Internet Explorer 11, the Content-Type setting is not functional and may cause issues with certain functionalities

My initial attempt to solve the issue involved using the method beginQuoteFileUnquoteUpload1, which created a proper boundary and Content-Type. However, upon receiving the file, I discovered that it was corrupted :( var formData = new FormData(); formD ...

Angular 6: TypeError - The function you are trying to use is not recognized as a valid function, even though it should be

I'm currently facing a puzzling issue where I'm encountering the ERROR TypeError: "_this.device.addKeysToObj is not a function". Despite having implemented the function, I can't figure out why it's not functioning properly or callable. ...

ReactJS error: Unable to access the setState property

As a newcomer to ReactJS, I have been facing some challenges. I recently familiarized myself with the ES6 syntax, and it claims that the following pieces of code are equivalent in meaning. 1. YTSearch({key: API_KEY, term: 'nba'}, function(vide ...

The MuiThemeProvider.render() function requires a valid React element to be returned, or null if necessary

I am working on creating a dropdown using Material UI and React. It renders perfectly when the dropdown component is in my src/app.js, but I encounter errors when I move it to a separate file named fruits.js: MuiThemeProvider.render(): A valid React el ...

Creating code in AngularJS

I have the following template structure: <h1 class="text-center" ng-bind-html="row.text"></h1> When the content of my row.text is a string like this: Hi your name is {{ name }} It will display as shown below: Hi your name is {{ name }} ...

Transform an angular1 javascript circular queue implementation for calculating rolling averages into typescript

I am currently in the process of migrating a project from Angular 1 to Angular 2. One of the key components is a chart that displays a moving average line, which requires the use of a circular queue with prototype methods like add, remove, and getAverage. ...

Using JavaScript to retrieve and compare element values for a total sum

Given two arrays, the goal is to determine if any two numbers in the array add up to 9. The function should return either true or false. For example: array1 [1, 2, 4, 9] has no pair that sums up to 9, so it returns false array2 [1, 2, 4, 5] does have a ...

"Utilize Ajax and PHP to seamlessly upload a PDF file directly into a MYSQL database

I am trying to figure out how to upload a pdf file from user input into my MySQL database. I have provided code that displays a user registration form with the option to upload a PDF file. My goal is to use AJAX to post this data to a PHP script for storag ...

Navigating through concatenated JSON strings in a web browser: A step-by-step guide

I am currently using Socket.IO to transmit data to the browser. The information being sent is a continuous stream of JSON objects, which upon arrival at the browser, transforms into a single large JSON string. However, the issue I am encountering is that t ...

Incorporate one element into another

Is it possible to use one component within another component based on a condition? For example: If the condition is true, call the component. I tried using v-html but it did not work. Is there another way to achieve this? ...

The project is not being recognized by 'webpack' when running within it

Every time I attempt to execute 'webpack' in my project, the command line shows me this error message: 'webpack' is not recognized as an internal or external command, operable program or batch file. I have installed webpack using th ...

Deleting an element in an Array of objects using Typescript

export class AppComponent implements OnInit { title = 'bucketList'; bucketList: BucketListItem[] = [ new BucketListItem( "Goa Trip", "Travel to Goa" ) ]; ngOnInit() { } onItemAdded(eventData) ...

Modifying arrays in ReactJS

Having trouble editing my array list, need some help. I can update a single input value successfully, but struggling with updating the entire array. Any suggestions on why the method isn't working and how to edit the array? When I try to store data ...

Can the hexadecimal code for a particular color name be identified?

Similar Question: Javascript function to convert color names to hex codes Is there a way to determine the hexadecimal value of a named color that is currently being used by the browser? For example, I would like to achieve something similar ...

Incorrect SQL Server DateTime referencing when using .NET Core framework causes insertion and updating errors

Having some issues while trying to store DATETIME values in my SQL Server database using .NET Core & Entity Framework. The data is fetched from a VueJS API call and sent in this format: ... lastModified: "2019-10-28T10:54:07.556Z" ... Upon receiving the ...

The styled-components seem to be having trouble injecting the necessary CSS to handle all the various props

I am curious to understand the potential reasons for styled-components not injecting all the necessary CSS into a page's header. In an existing project, I have defined a simple button like this: const Button = styled.button` background-color: ...

Vue.js axios method returns undefined; v-for directive fails to iterate - Issue on Wordpress site

Using a shortcode, I have integrated Vue.js into a Wordpress page. pl2010_vue_init_directory = pl2010_vue_init_directory || (function(ctx) { new Vue( { el: '#'+ctx.el, data: { errorMsg: "", successMsg: "", show ...

Changing the text color of the Vuetify Table header is a simple way to customize the

I am currently working on a Vuetify table with the class condition-table. I have applied the following CSS styling: .condition-table { background-color: #e1f5fe70; } The styling seems to work fine so far. However, when I added this additional CSS: .co ...