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

Discovering the selected href URL using JQuery or JavaScript

How can I detect the clicked href URL using JQuery when no ID is being used? For example, if I have a list of links where some redirect to new pages and others call javascript functions to expand a div. What approach should be taken in JQuery/Javascript ...

Sorry, there was an error with Vue-i18n: Unable to access the 'config' property because it is undefined

Let's start by examining what functions correctly in App.js import router from './routes.js'; import VueI18n from 'vue-i18n'; const messages = { en: { message: { hello: 'hello world' } } } // Create ...

Fetch Timeout Issue in React Native

I am currently using fetch to retrieve data from a server. Unfortunately, I am facing issues with setting a timeout for the fetch request in case the server does not respond. This is my global fetchData class: fetchGetResp(url, token) { return fetch( ...

Issue with Socket.IO: socket.on not executed

Recently, I devised a custom asynchronous emitter for implementing a server -> client -> server method. Regrettably, the functionality is not meeting my expectations. Although it emits the event, it fails to execute the callback as intended. Upon a ...

Using Three.js: Cloning Mesh and Material to Easily Toggle Clone Opacity

By using the command Mesh.clone();, it is possible to duplicate the mesh. Upon further investigation, I discovered that both the geometry and material are preserved in the clone. However, my goal is to independently adjust the opacity of each mesh. This le ...

Changing an array with VueJS

I have encountered a strange issue while using vuex to store state. It appears that there is a problem with changing the id of one of my objects. During my action, I am fetching data about a specific note saveNote({commit}, noteInfo) { var for ...

The content will only be visible when a comment is added and then removed

Currently, I am in the process of implementing an expansion panel that triggers an API call upon being clicked. This call then populates the v-card and v-layout components with the response data. However, a challenge I am encountering is that initially, th ...

Understanding the Difference Between WARN and ERR in npm Peer Dependency Resolution

I encountered a puzzling situation where two projects faced the same issue, yet npm resolved them differently: https://github.com/Sairyss/domain-driven-hexagon npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! W ...

Error: The 'price' property is undefined and cannot be read at path C:NODEJS-COMPLETE-GUIDEcontrollersshop.js on line 45, character 37

I have been attempting to add my products to the cart and calculate the totalPrice, but I keep encountering an error. Here is the error message:- enter image description here. Below is the code from my shop.js file:- exports.postCart = (req, res, next) =&g ...

Utilize AngularJS to create a concealed input field

Currently utilizing angularjs, you can find the code at this link Desired Outcome: When the add button is clicked, I want the value of $scope.todotest to appear along with the text in the textbox. Issue Faced: Upon adding for the first time, the date d ...

Using forEach in React to simultaneously set multiple properties and return destructured output within the setState function

The following is the initial code snippet: setRows((rows) => rows.map((row) => selected && row.node === selected.id ? { ...row, row.a: "", row.b: "", row.c: "" } ...

Tips for adjusting div content to fit a fixed height on all devices

Looking to adjust the size of the #left-content div based on the height of the window, while ensuring that all content is visible within the fixed #left-bg. However, when viewing on mobile or tablet devices, the content appears hidden. .left-bg{ backgro ...

The main attribute in the NPM package.json is missing or has no appropriate entry

I'm really struggling to figure out the best approach for setting up my package.json file. I have a JavaScript module that contains multiple reusable JS files, let's call it Module1. In Module1's package.json, the name attribute is set to " ...

A JavaScript alert function that triggers no matter the return value

An alert is being sent by a function when a radio box's value returns as null, even though it should have a value that is not null. The issue lies in another function on the page that hides the tables where these radios are located, making it difficul ...

Error encountered in TypeScript's Map class

When working with TypeScript, I keep encountering an error message that reads "cannot find name Map." var myMap = new Map(); var keyString = "a string", keyObj = {}, keyFunc = function () {}; // assigning values to keys myMap.set(keyString, "val ...

Vue.js: axios unexpectedly running synchronously across multiple components instead of asynchronously

Upon initializing my component, I am attempting to load ajax data. However, I have noticed that this causes other items loaded via ajax in the created() method to load synchronously rather than asynchronously. When this specific ajax request is triggered, ...

The variables in Next.js reset every time I navigate to a new page

Looking for a way to share a variable between pages in my Next.Js application, I have the following setup in my _app.js file: import { useState } from 'react'; const CustomApp = ({ Component, pageProps }) => { // Variables const [testVa ...

Encountering issues with compiling the Firebase NPM package on Vue 3

After adding firebase as an npm package and importing it into the vue project, I encountered a specific error when attempting to run the project. The error message stated: ERROR Failed to compile with 1 error ...

Utilizing Google Language API for bulk translation tasks

My current project involves using Google's AJAX Language API to translate each element in an array. for(var i=0; i < mytext.length; i++) { google.language.translate(mytext[i], originalLanguage, newLanguage, function(result){ if(!result.error){ ...

Tips for resolving the error: finding the right loader for handling specific file types in React hooks

data = [{ img: '01d' }, { img: '02d' }] data && data.map((item) => ( <img src={require(`./icons/${item['img']}.svg`).default} /> )) I am facing an issue with the message Error: Module parse failed: U ...