Using Vuejs to pass the SAVE function into a CRUD component

I am facing a challenge in finding a suitable solution that involves advanced parent-child communication in Vue.js. The scenario is such that there are multiple parent components, each with its own logic on how to save data. On the other hand, there is only one child component that houses a list of elements and a form for creating new elements, but lacks knowledge on how to save the data.

The dilemma is: Is there an alternative (better) approach to achieve the same functionality without relying on this.$refs.child references? I am contemplating if it's possible to simply pass a function (SaveParent1(...) or SaveParent2(...)) to the child component. However, the issue lies in the fact that these functions contain certain variables from the parent that may not be accessible in the child context and these variables could change during runtime.

Some clarifications:

  1. In reality, the methods SaveParent1 and SaveParent2 return a Promise (axios).
  2. The child-component serves as a CRUD used throughout different sections.

Currently, the communication pattern looks like this: CHILD -event-> PARENT -ref-> CHILD.

Below is an example:

<div id="app">
  <h2>&#128512;Advanced Parent-Child Communication:</h2>
  <parent-component1 param1="ABC"></parent-component1>
  <parent-component2 param2="XYZ"></parent-component2>
</div>
Vue.component('parent-component1', {
  props: { param1: { type: String, required: true } },
  methods: {
    onChildSubmit(p) {
        // Here will be some logic to save the param. Many different parents might have different logic and all of them use the same child component. So child-component contains list, form and validation message but does not know how to save the param to the database.
      var error = SaveParent1({ form: { p: p, param1: this.param1 } });
      if (error)
        this.$refs.child.paramFailed(error);
      else
        this.$refs.child.paramAdded(p);
    }
  },
  template: `<div class="parent"><p>Here is parent ONE:</p><child-component ref="child" @submit="onChildSubmit"></child-component></div>`
});

Vue.component('parent-component2', {
  props: { param2: { type: String, required: true } },
  methods: {
    onChildSubmit(p) {
        // Here is a different logic to save the param. In practice it is going to be different requests to the server.
      var error = SaveParent2({ form: { p: p, param2: this.param2 } });
      if (error)
        this.$refs.child.paramFailed(error);
      else
        this.$refs.child.paramAdded(p);
    }
  },
  template: `<div class="parent"><p>Here is parent TWO:</p><child-component ref="child" @submit="onChildSubmit"></child-component></div>`
});

Vue.component('child-component', {
  data() {
    return {
      currentParam: "",
      allParams: [],
      errorMessage: ""
    }
  },
  methods: {
    submit() {
        this.errorMessage = "";
        this.$emit('submit', this.currentParam);
    },
    paramAdded(p) {
        this.currentParam = "";
        this.allParams.push(p);
    },
    paramFailed(msg) {
        this.errorMessage = msg;
    }
  },
  template: `<div><ol><li v-for="p in allParams">{{p}}</li></ol><label>Add Param: <input v-model="currentParam"></label><button @click="submit" :disabled="!currentParam">Submit</button><p class="error">{{errorMessage}}</p></div>`
});

function SaveParent1(data) {
  // Axios API to save data. Below is a simulation.
  if (Math.random() > 0.5)
    return null;
  else
    return 'Parent1: You are not lucky today';
}

function SaveParent2(data) {
  // Axios API to save data. Below is a simulation.
  if (Math.random() > 0.5)
    return null;
  else
    return 'Parent2: You are not lucky today';
}

new Vue({
  el: "#app"
});

A live demo is also available: https://jsfiddle.net/FairKing/novdmcxp/

Answer №1

From an architectural standpoint, my recommendation is to create a service that is completely separate from the component hierarchy. This service can be injected and utilized in each of the components. By implementing this type of component hierarchy and architecture, you can avoid running into common issues. It's crucial to abstract as much functionality and business logic away from the components as possible. In modern frameworks, components should be viewed as enhanced HTML templates, acting primarily as controllers. Keeping components simple and lightweight will help prevent potential problems. Although I am not familiar with vue.js, I hope this guidance gives you some direction.

Answer №2

I believe I've come up with a solution that eliminates the need for two-way communication. By passing a method to the child component, it can handle everything independently without needing to communicate back to the parent. I'm satisfied with this approach and have marked it as the answer. Thank you to everyone for your assistance.

What are your thoughts on this strategy?

Below is the code snippet showcasing my solution:

<div id="app">
  <h2>&#128512;Advanced Parent-Child Communication:</h2>
  <parent-component1 param1="ABC"></parent-component1>
  <parent-component2 param2="XYZ"></parent-component2>
</div>
Vue.component('parent-component1', {
    props: { param1: { type: String, required: true } },
  computed: {
    saveFunc() {
        return function(p) { SaveParent1({ form: { p: p, param1: this.param1 } }); }.bind(this);
    }
  },
  template: `<div class="parent"><p>Here is parent ONE:</p><child-component :saveFunc="saveFunc"></child-component></div>`
});

Vue.component('parent-component2', {
    props: { param2: { type: String, required: true } },
  computed: {
    saveFunc() {
        return function(p) { SaveParent2({ form: { p: p, param2: this.param2 } }); }.bind(this);
    }
  },
  template: `<div class="parent"><p>Here is parent TWO:</p><child-component :saveFunc="saveFunc"></child-component></div>`
});

Vue.component('child-component', {
    props: { 
    saveFunc: { type: Function, required: true }, // This is gonna be a Promise in real life.
  },
  data() {
    return {
      currentParam: "",
      allParams: [],
      errorMessage: ""
    }
  },
  methods: {
    submit() {
        this.errorMessage = "";
      var error = this.saveFunc(this.currentParam);
      if (error)
        this.paramFailed(error);
      else
        this.paramAdded(this.currentParam);
    },
    paramAdded(p) {
        this.currentParam = "";
        this.allParams.push(p);
    },
    paramFailed(msg) {
        this.errorMessage = msg;
    }
  },
  template: `<div><ol><li v-for="p in allParams">{{p}}</li></ol><label>Add Param: <input v-model="currentParam"></label><button @click="submit" :disabled="!currentParam">Submit</button><p class="error">{{errorMessage}}</p></div>`
});

function SaveParent1(data) {
    console.log(data);
    // Axios API to save data
    if (Math.random() > 0.5)
    return null;
  else
    return 'Parent1: You are not lucky today';
}

function SaveParent2(data) {
    console.log(data);
    // Axios API to save data
    if (Math.random() > 0.5)
    return null;
  else
    return 'Parent2: You are not lucky today';
}

new Vue({
  el: "#app"
});

The live demo can be accessed via this link: https://jsfiddle.net/FairKing/novdmcxp/126/

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

Having trouble deploying my Express/Next app on Netlify

I am facing issues deploying my Next/Express app on Netlify. While the app functions perfectly locally, I encounter problems when attempting to deploy it using Netlify lambda function. Here are the links to my test git repositories: https://github.com/La ...

What is the reason behind obtaining a distinct outcome when logging the properties of an object compared to logging the object itself and checking its properties?

Currently, I am working on integrating socket-io with react redux and encountering a peculiar namespace problem. console.log(socket); console.log(socket.disconnected); console.log(socket.id); console.log(socket); The first log displays a comprehensive ob ...

Connect data from an HTML table depending on the chosen option in a dropdown menu using AngularJS, JQuery, JSON, and

Could you please correct my errors? It's not working as I have made some mistakes. I need an HTML table based on the selection. I have tried but cannot find a solution. I created a dropdown, and if I select any value from the dropdown and click a butt ...

What causes jQuery's .width() method to switch from returning the CSS-set percentage to the pixel width after a window resize?

After exhaustively console logging my code, I have finally identified the issue: I am attempting to determine the pixel width of some nested divs, and everywhere I look suggests that jQuery's .width() method should solve the problem. The complication ...

Converting an HTMLElement to a Node in Typescript

Is there a method to transform an HTMLElement into a Node element? As indicated in this response (), an Element is one specific type of node... However, I am unable to locate a process for conversion. I specifically require a Node element in order to inp ...

Run a Javascript function two seconds after initiating

My goal is to implement a delay in JavaScript using either setInterval or setTimeout, but I am facing an issue where the primary element is getting removed. Code that works fine without Javascript delay: const selectAllWithAttributeAdStatus = document. ...

What is the efficient way to toggle localStorage based on checkbox selection using jquery?

I am looking to efficiently manage localStorage using checkboxes. When a checkbox is checked, I want to add the corresponding value to localStorage, and remove it when unchecked. var selectedModes = new Array(); $('.play_mode').on('click& ...

Update the state within a different function in Vue.js

Just starting out with Vue.js and I'm trying to figure out how to update the component's state from a function in another file. I have a basic form with only an input file element. Once the user selects a file, the onChange handler will be trigg ...

Attempting to utilize the Optimist API's help() function to display the usage() information

I am relatively new to using optimist and despite my attempts at researching and experimenting, I have been unable to find a streamlined method for incorporating a --help option. In the documentation, there is mention of a help() function. Based on this i ...

What are some ways to make autorun compatible with runInAction in mobx?

Currently delving into the world of mobx and runInAction, facing a challenge in comprehending why autorun fails to trigger my callback in this particular scenario: class ExampleClass { // constructor() { // this.exampleMethod(); // } ...

Using Angular 4 to delete selected rows based on user input in typescript

I am facing a challenge with a table that contains rows and checkboxes. There is one main checkbox in the header along with multiple checkboxes for each row. I am now searching for a function that can delete rows from the table when a delete button is clic ...

Testing NestJS Global ModulesExplore how to efficiently use NestJS global

Is it possible to seamlessly include all @Global modules into a TestModule without the need to manually import them like in the main application? Until now, I've had to remember to add each global module to the list of imports for my test: await Tes ...

The ongoing saga of `npm run dev` seems to have no end in sight

I've been attempting to integrate Vue into my Laravel project, and I've followed all the necessary steps: Installed Laravel/UI using composer require laravel/ui Ran php artisan ui vue Included the in my main layout file app.blade.php Ran npm ru ...

React.js issue with onChange event on <input> element freezing

I am experiencing an issue where the input box only allows me to type one letter at a time before getting stuck in its original position. This behavior is confusing to me as the code works fine in another project of mine. const [name, setName] = useStat ...

Using Jquery to handle input data in a form

Using jQuery, I have set up an AJAX function to fetch data from a database in real-time as the user fills out a form with 5 input fields. Currently, my code looks like this: $("#searchtype, #searchtext, #searchtag, #daterangefrom, #daterangeto").on("load ...

An issue arose when trying to display React components within an Angular application

Attempting to incorporate React components into an Angular 7 application has been a challenge for me. While I have successfully rendered simple React components, I encountered the following error message (displayed in the browser console) when attempting t ...

Give a class to the element contained within an anchor tag

One way to add a class to the <a>-tag is through this line of code. $("a[href*='" + location.pathname + "']").addClass("active"); However, I am looking to add the class to an li element inside the <a>-tag. What would be the best ap ...

Is there a RxJS equivalent of tap that disregards notification type?

Typically, a tap pipe is used for side effects like logging. In this scenario, the goal is simply to set the isLoading property to false. However, it's important that this action occurs regardless of whether the notification type is next or error. Thi ...

Issue: The error message "articales.forEach is not a function" is indicating

app.get('/', (req, res) => { const articales = { title: 'Test Articles', createdAt: Date.now(), description: "Test Description" } res.render('index', { articales : articales }) }) <div ...

Testing event emitters in node.js: a step-by-step guide

Imagine the scenario where I need to create a basic task. However, I also need to develop a test that validates the following criteria: The task should emit an object. The emitted object must have a property named "name". I am utilizing mocha and chai e ...