Using VueJs to invoke a plugin from a .js file

I'm seeking a deeper understanding of working with vueJS.

My current setup

In my Login.vue component, there is a function logUser() from UserActions.js which in turn calls the postRequest() function from AxiosFacade.js

Additionally, I use a plugin to display Toast information using

createApp(App).use(Toaster).mount('#app')
and trigger the toaster with
this.$toast.show(`Default Toast Message`)

What I aim to achieve

I want to be able to call this.$toast.show from the catch blocks of Axios calls in AxiosFacade.js

For example:

return axios.post(`${serv}/${ressource}`,
    {
        data: params,
    },
    {headers: {'Authorization': 'Bearer ' + token}})
    .then((response) => response = response.data)
    .catch((err) => {
        this.$toast.error(err.response.data.message);
        throw err.response.data.message
    })

However, I am unsure about how to establish connections between .js and .vue files

PS: My next objective is to create my own Toaster.vue component and control it (showing/hiding) from AxiosFacade.js. Any advice on this would be appreciated :)

Thank you!

Answer №1

Imagine if you were to eliminate the catch part from your axios function

return axios.post(`${serv}/${ressource}`,
{
    data: params,
},
{headers: {'Authorization': 'Bearer ' + token}})
.then((response) => response = response.data)

and handle it where you want to display the toast. Login.vue:

function logUser () {
  return postRequest()
    .then(responseData => {
      //do your stuff
    })
    .catch((err) => {
      this.$toast.error(err.response.data.message)
      throw err.response.data.message
    })
}

Update:

The solution is actually pretty straightforward. Simply add your method where this needs to refer to the vue instance in your component.

Check out the following example:

accessVueInstance.js:

export function compare(vueInstance) {
  return this === vueInstance
}

MyComponent.vue:

import the function

import { compare } from "./accessVueInstance"

add the function to your component:

If you use class components:

export default class MyComponent extends Vue {
compare = compare

created() {
console.log(this.compare(this)) //will log true
}
//your stuff
}

Else:

methods: {
compare
},
created() {
console.log(this.compare(this)) //will log true
}

vue docs

Vue automatically binds the this value for methods so that it always refers to the component instance.

See it in action codesandbox.io

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

Restart animation following a scroll occurrence

My experiment involves using the anime.js framework to create a simulation of leaves falling from a tree. The animation triggers when the user scrolls to the top of the page. However, I am facing an issue where the animation only plays once; if the user sc ...

Issue with React Routes only occurring in the production website

I'm encountering an issue on my personal website that only occurs in production, but not in my local environment. Here's the situation: I have set up the routes as follows const Routes = () => ( <Router> <Route exact path=&quo ...

Tips for minimizing the transfer time of large arrays using ajax

https://i.stack.imgur.com/IP0oe.pngDescription I am currently working on transferring a JSON object from the server to the client using PHP and JavaScript via AJAX. The JSON object contains a large array (200x200) of integers. The server is running on lo ...

How to enable real-time file changes detection in sails for development

I recently embarked on a new project using Sails (built on Express and Node.js). Currently, I am initiating my server with the command: sails lift However, whenever I make changes to the codebase, I need to manually restart the server. Is there a way to ...

When to Utilize State Versus Getters in Vuex?

When it comes to extracting data from Vuex, there are scenarios where the decision between using getters and accessing state directly is quite evident. For instance: If I simply need a single value, like the count variable, then accessing the state direc ...

Tips for extracting information from Firebase and showing it on a Google gauge chart

I'm having some trouble displaying data from Firebase on a gauge chart. I keep getting an error that says "Uncaught (in promise)". Here's the JavaScript code I've been working with: <script type="text/JavaScript"> google.ch ...

Adjust grading system based on user interaction with JavaScript

I am currently working on a grading system for a website and I am attempting to modify the interpretation of grades when a column is clicked. Specifically, I am looking to convert Average (%) to Letters to 4.0 Grade Average. To achieve this, I am using Jqu ...

Looking to retrieve the full browser URL in Next.js using getServerSideProps? Here's how to do

In my current environment, I am at http://localhost:3000/, but once in production, I will be at a different URL like http://example.com/. How can I retrieve the full browser URL within getServerSideProps? I need to fetch either http://localhost:3000/ or ...

Activate Angular Material's autocomplete feature once the user has entered three characters

My goal is to implement an Angular Material Autocomplete feature that only triggers after the user has inputted at least three characters. Currently, I have it set up so that every click in the input field prompts an API call and fetches all the data, whic ...

Setting up a div as a canvas in Three.js: Step-by-step guide

Is there a way to adjust the JavaScript in this three.js canvas example so that the scene can be contained within a specific div element on a webpage? Here is the example: https://codepen.io/PedalsUp/pen/qBqvvzR I would like to use this as the background ...

Guide on how to receive multiple responses from a single ajax request in PHP

I am in the process of developing a web application that includes a search feature. When a user enters a name to search for, I use an AJAX request to retrieve and display records related to that specific person. However, due to the extensive amount of info ...

Is it possible to utilize axios in Vue while utilizing CORS in the API?

I am encountering an issue with making a GET request to a CORS enabled corona virus API using axios and Vue. I have no control over their server, and my Vue app was created with vue-cli. Interestingly, I am able to make two requests from different APIs - ...

What is the best method for transferring states between components?

When it comes to React JS, I am a beginner looking to develop a ToDo list application. In my project, I have the main page App.js, where I created the component MainBlock. This MainBlock component structures the layout into left and right sides. On the rig ...

Monitor the DOM for visibility changes in Selenium WebDriver and PjantomJS before proceeding

I am currently creating automated test scripts using selenium-webdriver, phantomJS, and mocha. The script file I'm working with is a JavaScript file. My goal is to wait until an element (<a>) is fully visible before clicking on it. Let me pro ...

Guide to loading a minified file in Angular 2 with Gulp Uglify for TypeScript Bundled File minimization

In my Angular 2 application, I have set the TypeScript compiler options to generate a single outFile named Scripts1.js along with Scripts1.js.map. Within my index.html file: <script src="Scripts/Script1.js"></script> <script> ...

Verify if the nested arrays within the object consist of any empty elements

Take a look at the object below: { "params": { "time_to_diagnosis": [ { "field": "date_of_diagnosis", "value": "" }, { "field": "date_of_symptom_onset", "value": "2019-09-01" } ], "time ...

Identifying overflow of text or elements in JavaScript during execution

The website I'm working on has a unique design that requires users to scroll horizontally using the Arrow Keys instead of swiping. To achieve this, I must constantly check for overflow in text or elements each time a new page is loaded, and if necessa ...

Unable to transmit a collection of JavaScript objects in a node.js environment

Below is the code snippet I am currently working with: app.get('/posts',function(req,res){ console.log(posts); res.send(posts); res.send(200); }); I am using the following approach to retrieve and display an array of JavaScript objects (posts ...

The wrap() method in jQuery clones elements multiple times

I have created a simple function that wraps a div tag inside another div tag when the browser window exceeds a certain width of x pixels. However, I've encountered a strange bug when resizing the page more than once. Let me share with you the jQuery ...

Navigating through events within React

I'm working on creating a login page, where upon clicking the submit button it should navigate to the Dashboard page. However, I seem to be encountering an issue with my code. After entering login details and clicking on the login button, the details ...