Efficient initialization process in Vue.js components

Upon initialization of a component, the data callback is executed as follows:

data(){
    return {
        name: myNameGetter(),
        age: myAgeGetter(),
        // etc...
    }
},

Following that, a notification is sent to a parent component regarding logic from this particular component:

created(){
    this.$emit('personFullName', this.getFullName());
},

The same logic is then implemented within the watchers as well:

watch: {
    person: function(){
        this.name = myNameGetter();
        this.age = myAgeGetter();
        this.$emit('personFullName', this.getFullName());
    }
}

Is there a more efficient way to handle this?

The only solution I have thought of so far is:

watch: {
    person: function(){
        const data = this.data();
        for (let key in data) this[key] = data[key];
        this.$emit('personFullName', this.getFullName());
    }
}

However, it still seems somewhat redundant. How has the community addressed this issue?

Answer №1

Imagine a scenario where instead of an example, we are discussing a real-life app such as a calendar. Within this calendar container, there are components for the header, month view, week view, and day view. The title in the container is determined by the child component - if it's the month view, it emits "March 2017", while the day view emits "31st March". However, the challenge lies in repeatedly calling the getter function during initialization, watch events, and emitting to the parent upon creation. This repetition is what I aim to streamline.

In a previous Vue project, I created a date/time picker bearing similarities to your Calendar setup. It consisted of a container (DateTimePicker) with two child components (DatePicker and TimePicker), each visible based on whether editing the date or time. Perhaps restructuring how data is shared among components could enhance efficiency. Are the child components solely responsible for determining the title? Since all child components share the same Date object, shouldn't the Calendar component decide the title dynamically?

Shouldn't the responsibility of determining the title fall on the Calendar component rather than the child ones? By devising a structure where the Calendar determines the displayed title based on the current child component, you can simplify the process:

<div class="calendar">
  <div class="cal-title">{{ title }}</div>
  <day v-if="view === 'day'" :value="date" @input="onInput"></day>
  <week v-if="view === 'week'" :value="date" @input="onInput"></week>
  <month v-if="view === 'month'" :value="date" @input="onInput"></month>
</div>
{
  props: ['date'],

  data() {
    return {
      view: 'day',
      // This component has no internal state for the date
    };
  },

  computed: {
    title() {
      switch (this.view) {
        case 'day': return this.date.format('day'); break;
        case 'week': return this.date.format('week'); break;
        case 'month': return this.date.format('month'); break;
      }
    },
  },

  methods: {
    onInput(date) {
      this.$emit('input', date);
    },
  },
}

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

Function defined as an AngularJS component

I am facing an issue where my component is not initializing when I create it with a function that returns a component object. Can someone please help me understand the difference between these two situations? Html: <div ng-app="demoApp"> <navb ...

Update the content within every <td> element using AJAX/JQUERY on a table created from JSP

I have a database filled with descriptions and corresponding ID numbers. The table displays them like this: index.jsp <table> <tr> <td>Name:</td> <td>Id:</td> </tr> <c:forEach items ...

Guide to integrating a Custom Font into live data on a PDF file with the help of jsPDF

I recently successfully converted a dynamic webpage to PDF using jsPDF and now I'm looking to customize the font family of the PDF document. Is there an option for this in jsPDF? Please advise, thank you! Here is my code snippet: <div id="#p ...

Enhance your Highmap R or JavaScript visualization with a unique custom legend feature

Provided below is my code snippet, output$map <- renderHighchart({ region_map = hcmap("countries/nz/nz-all") highchart(type = "map") %>% hc_title(text = "Average") %>% hc_add_series_map(map = region_map, df = data1, joinBy = " ...

Using Kendo Grid to Transfer Data Between Grid Cells

Recently, I encountered a problem in my Kendo MVC project where I needed to drag a product code from one Kendo Grid to another when the cell value was empty. Here's the scenario: Grid A contains products ordered, but the vendor sending the list has i ...

Determining the selected option's value made by the user

On my index.php file, which contains the form and function, I have the following code: $(function() { $.ajax({ type: "POST", url: "invtype.php", data: "getrevenuetype=true", success: function(b){ $("#revenue ...

The issue of underscorejs being undefined arises when trying to load it using both XMLHttpRequest and

I am attempting to dynamically load underscorejs using XMLHttpRequest and eval function function includeScriptSync(scriptUrl) { var xmlhttp = new XMLHttpRequest(); xmlhttp.open("GET", scriptUrl, false); xmlhttp.onreadystatechange = function() ...

What steps can be taken to avoid an abundance of JS event handlers in React?

Issue A problem arises when an application needs to determine the inner size of the window. The recommended React pattern involves registering an event listener using a one-time effect hook. Despite appearing to add the event listener only once, multiple ...

Explaining how to iterate through objects (one by one) in the This.questionnaire.Profile at every click using JavaScript (answer not found in forums)

Creating a series of questions, each part being stored in This.question = {p1: {...}, p2: {...}, p3: {...}, p4: {...}, p5: {...} etc. (and many more). I want to be able to switch from one article to the next every time I click a button... click => next ar ...

Information on the Manufacturer of Devices Using React Native

Struggling to locate the device manufacturer information. Using the react-native-device-info library produces the following output. There seems to be an issue with handling promises. I need to store the device manufacturer value in a variable. const g ...

The connection was refused by hapi.js

We have recently encountered an issue while using hapijs: hapi, {"code":"ECONNREFUSED","errno":"ECONNREFUSED","syscall":"connect","domainEmitter":{"domain":{"domain":null,"_events":{},"_maxListeners":10,"members":[]},"_events":{},"_maxListeners":10},"doma ...

Can anyone share a straightforward yet practical demonstration of using jquery.JsPlumb?

In my quest for a reliable graph-visualization JavaScript library, I recently came across jsPlumb at http://jsplumb.org. The examples I've seen truly showcase its advanced capabilities and attractive design. However, despite the extensive documentatio ...

Tips for effectively testing an Angular directive

I'm having trouble testing an Angular directive due to encountering the following unexpected error: Error: Unexpected request: GET /api/players/info It seems that the issue may stem from references to my controller within the directive definition ob ...

Create a compressed package of a Vue project that can easily be inserted into a Blogger blog post as a single HTML file

Is there a way to package all the files related to a Vue.js project (HTML, JavaScript, CSS) into one single HTML file for easy deployment on a Blogger Blogspot post? In the past, a question similar to this was asked regarding bundling files into a single ...

Navigating through a collection of objects

My array consists of objects, each having the following structure: var car = { make: "", model: "", price: "" } I am attempting to iterate through each object and check if a specific property is defined in this manner: for (i = 0; i <= ...

What could be the reason behind encountering an NaN error while using these particular functions?

I recently delved into the world of JavaScript, starting my learning journey about two months ago. While going through a few tutorials, I stumbled upon an intriguing project idea. However, I've hit a roadblock that's impeding my progress. Every t ...

Error: Unable to access attributes of null object (specifically 'accessToken')

After following a YouTube tutorial by Lama for creating an E-commerce application, I attempted to add a logout feature on the admin page that was not covered in the tutorial. To implement this, I used Redux to grab the currentUser and set it to null to suc ...

Trigger the fire event on .click() except when text is being selected

I am currently working on a chat box project and I want the input field within the message area to automatically get focused when the user clicks anywhere in the chat box. However, I don't want this functionality to interfere with text selection for c ...

Tips for validating an email address using ReactJS

I'm currently working on customizing the email verification process for a signup form in ReactJS. My goal is to replace the default email verification with my own validation criteria. Initially, I want to ensure that the entered email address contains ...

How can I pull the account creation date stored in MongoDB and display it using Handlebars?

Currently in my development, I am utilizing MongoDB, NodeJS, and Handlebars. My challenge is to convert the user.id into a timestamp and then display this timestamp on my HTML page. At present, I can display the user.id by using {{ user.id }} in my code, ...