Vuejs - Display multiple dates within one component

I have developed various components (such as tables, selects, etc) that all rely on the same methods to access API information.

The main objective is to be able to use these components across different pages of the application in a way that allows for flexibility. In order to achieve this, I have implemented multiple methods to enable seamless integration regardless of the data being retrieved.

However, applying these methods to every component that interacts with the API would result in redundancy and unnecessary repetition of code. Therefore, the aim is to create these methods at a global level.

Upon researching possible solutions, I came across three potential approaches: Plugins, Mixins, and Vuex. Yet, I am unsure about which method would be the most optimal for achieving this goal.

Any recommendations or insights?

Answer №1

Consider using Redux for state management in your Vue.js applications.

By setting up a centralized store, your components can easily interact with the data using selectors, actions, and reducers. The store acts as the middleman between the components and the API.

For instance, you can make your table component simple and dumb by passing data to it from the parent component. This data can be accessed through a selector or directly from the store's state in the parent component.

When a component needs to send data to the API, it can trigger an event that the parent listens to and then dispatches the appropriate action to the Redux store. The store handles the interaction with the API without the parent needing to know the specifics.

If you want to see an example of this in action, check out my todo application on GitHub. It uses Vue.js with Redux for state management and stores data in MongoDB. You can easily modify the store to use REST methods like get, post, put, delete, etc.

You can find all the relevant code in files such as App.vue, store.js, and a line in main.js to connect the store to the Vue instance.

Answer №2

Utilizing Vuex can streamline the management of shared and individual component states. However, if you're struggling with handling shared API calls directly through Vuex persistence, it may not provide a direct solution. Its effectiveness lies in facilitating data accessibility for your components once the initial data retrieval is accomplished.

To address this issue, consider creating a dedicated module for API calls and data retrieval, such as:

http.js

export const getUser = async id => {      
  const response = await fetch(`/user/${id}`)
  return await response.json()
}

export const getContent = async id => {      
  const response = await fetch(`/content/${id}`)
  return await response.json()
}

This approach offers versatility by supporting both Vuex-dependent and standalone implementation, enabling seamless method invocation from any part of your application.

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

In Vue.js with Laravel mix, when the base URL includes a subfolder, here is how you can reference app.js

My website's domain for my Laravel web application is currently set to www.mywebsite.com/my-project/public and I prefer not to change it. After installing Vue.js using npm install && npm run dev, I attempted to reference app.js with the follo ...

"Looking to spice up your website with a dynamic background-image

I've encountered a problem with my CSS code for the header's background image. Despite trying various methods to create a slideshow, nothing seems to be working. Can someone provide guidance? I have four banner images named banner1, banner2, bann ...

What could be the reason my Virtual Mongoose categories aren't appearing?

Here is the description of my post model: const mongoose = require('mongoose'); const Schema = mongoose.Schema; const PostSchema = new Schema({ text: String, image: String, author: { type: Schema.Types.ObjectId, ref: 'user&ap ...

Obtain the value of an element from the Ajax response

Just starting out with Jquery and Ajax calls - here's what I've got: $(document).ready(function () { $.ajax({ type: "GET", url: "some url", success: function(response){ console.log(response); } }) }); Here's the ...

A complex valueOf function in Javascript

What is the purpose of using ({}).valueOf.call(myvar)? This expression converts any value to an object. If the input is already an object, it remains unchanged; however, if it is a primitive type, it gets converted to an instance of a wrapper type. I ...

Tips for navigating to a specific row within a designated page using the Angular Material table

Utilizing angular material, I have set up a table with pagination for displaying data. When a user clicks on a row, they are redirected to another page. To return to the table page, they must click on a button. The issue arises when the user needs to retu ...

Create a custom npm package that is compatible with frontend environments like create-react-app. Ensure you have a suitable loader in place to handle the specific file type of the module

After developing a node module and releasing it as a node package, I encountered an issue when trying to use it in frontend applications (specifically with a 'create-react-app'). The error message that appeared stated: Module parse failed: Unexp ...

Node.js routing currently lacks the ability to easily verify the presence of a JWT token for every route

I have a node application where, upon routing to ('/login') with valid credentials, I generate a JWT token with an expiry time and direct the user to the next page. If the user tries to access any other route directly (e.g., '/home') af ...

Playing with background hues

Can anyone help me with this issue? I've been attempting to change the background color using jQuery upon document load, but it doesn't seem to be working. Any thoughts on what I might be doing wrong? http://jsfiddle.net/KczZd/2/ HTML: <d ...

Updating/Timer feature for a single feed out of two -- Combining data with $q.all()

I'm revisiting a question I previously asked here. The approach I took involved using the $q.all() method to resolve multiple http calls and then filtering and merging the data. Everything was working fine, but now I want to refresh one of the feeds ...

What is the best way to extract value from a specific link using JavaScript?

I have a PHP script that retrieves data from a database: <?php while($trackResultRow = mysqli_fetch_assoc($trackResult)){?> <a onclick="remove()"><span class="glyphicon glyphicon-thumbs-down pull-right"></span></a> < ...

What approach do you recommend for creating unique CSS or SCSS styles for the same component?

Consider a scenario where you have a complicated component like a dropdown menu and you want to apply custom styles to it when using it in different contexts. This customization includes not only changing colors but also adjusting spacing and adding icons. ...

methods for extracting json data from the dom with the help of vue js

Can anyone help me with accessing JSON data in the DOM using Vue.js? Here is my script tag: <script> import axios from "axios"; export default { components: {}, data() { return { responseObject: "" }; }, asy ...

Fetch information from the input field and send it to the Redux state

Looking for a solution - I'm working on a simple todo app where I need to store user input value in the redux state. The input value is currently stored in local state until the user clicks the "add" button. The main issue : How can I pass this input ...

The X-Axis in FlotChart's setupGrid() function is not being properly updated

I am currently updating a real-time chart by pushing new data to an array. Despite calling setupGrid() and draw(), the X-Axis data on the chart does not update. this.plot = $.plot($("#chart"), [this.plotData], this.plotOptions); Within my method ...

I'm looking for a method to trigger onChange() specifically on Internet Explorer using only JavaScript, HTML, and CSS without relying on jQuery

Looking for a way to utilize onChange() only on Internet Explorer using Javascript, HTML, CSS (No Jquery). My current code successfully sends the input to my function upon onChange(), but it seems to work smoothly on Chrome and not on IE. Is there a meth ...

Updating backgroundPosition for dual background images within an HTML element using Javascript

Issue at Hand: I am currently facing a challenge with two background images positioned on the body tag; one floating left and the other right. The image on the left has a padding of 50px on the left side, while the image on the right has a padding of 50px ...

Creating a customized TextField look with styled-components and Material-UI's withStyles feature

Take a look at this customized TextField style with Material-UI's withStyles: export const StyledTextField = withStyles({ root: { background: 'white', '& label.Mui-focused': { color: 'white' }, ...

Issue: $injector:unpr Unrecognized Provider: itemslistProvider <-

I've spent several days debugging the code, but I can't seem to find a solution. I've gone through the AngularJS documentation and numerous Stack Overflow questions related to the error, yet I'm still unable to identify what's caus ...

What is the best way to bypass TS1192 when incorporating @types/cleave.js into my Angular application?

Using cleave.js (^1.5.2) in my Angular 6 application, along with the @types/cleave.js package (^1.4.0), I encountered a strange issue. When I run ng build to compile the application, it fails and shows the following errors: ERROR in src/app/app.component. ...