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

Error: Vue page disappears mysteriously post-build

Recently, I encountered an issue with a routing problem in my web application. Initially, the route was set as: http://localhost:8080/user/reset Everything worked fine during development. However, after building the project and placing it in the loca ...

When using AngularJS services to pass data, the data may be lost when the page is refreshed

I'm facing an issue with transferring data from controller A to controller B using a Factory (or a Service) when the user refreshes the browser. I am able to successfully set the data in controller A and retrieve it in controller B, but upon refreshin ...

Dealing with the Spread operator in React and Redux causes issues

As a newcomer to the world of React and Redux, I find myself facing compilation errors while working on a reducer due to my attempt to utilize the spread operator. export default function chaptersReducer( state = { chapters: {}, isFetching: false, error ...

Error: Unable to retrieve data through Ajax request

$(document).ready(function(){ /* Fetching Data from TTC for Union Station */ $.getJSON("http://myttc.ca/Union_station.json?callback=?", function(data){ if (routes.length > 0) { // Display the stop details with departur ...

Utilize dojo to manually trigger a window resize event

Is there a way to manually trigger the window resize event (the one that occurs when you resize your browser window) using Dojo? I need this functionality to dynamically resize my C3 Charts. I came across the on module in Dojo, which allows for listening ...

Difficulty encountered in closing dialog box upon clicking NavLink in React

Currently, I am developing a React application and have integrated a dialog box using the Material-UI library's Dialog component. Inside this dialog box, there is a navigation menu that I would like to close when a user clicks on one of the navigation ...

Tips for distinguishing individual rows within a table that includes rowspans?

My Vue application calculates a table with rowspans by using an algorithm based on a configuration file. This allows the application to render columns (and maintain their order) dynamically, depending on the calculated result. For example, see the code sn ...

How to Trigger a Child Component Function from a Parent Component in React.js

I want to trigger a function in my child component when a button is clicked in the parent component. Parent Component: class Parent extends Component{ constructor(props){ super(props); this.state = { //.. } } ...

What could be the reason for Jest flagging CSS as untested instead of identifying untested functions?

While working on my vue3 project and writing tests with jest, I have encountered an issue where jest is incorrectly marking the CSS within several single file components as untested, even though it doesn't need to be tested. Moreover, its assessment ...

Why is the lifecycle callback not being triggered?

I am currently learning how to develop with Vue.js. I have been trying to use the lifecycle callbacks in my code. In my App.vue file, I have implemented the onMounted callback. However, when I run the code, I do not see the message appearing in the consol ...

Is it possible to implement a component filter within a computed property in Vue?

Within a SFC, the code snippets I have are: filters: { localizedData: function () { return new Date(value).toLocaleString(); } } and computed: { todos() { return _.map(this.raw_todos, item => { return { ...

Retrieving information from an Object within a JSON response

After calling my JSON, I receive a specific set of arrays of objects that contain valuable data. I am currently struggling to access this data and display it in a dropdown menu. When I log the response in the console, it appears as shown in this image: htt ...

Contrasting the lib and es directories

I am seeking clarity on my understanding. I am currently working with a npm package called reactstrap, which is located in the node_modules folder. Within this package, there are 4 folders: dist es lib src I understand that the src folder contains the s ...

Press anywhere on the screen to conceal the AngularJS element

Attempting to create a toggle effect using 2 ng-click functions. One is bound to a button, the other to the body tag. The goal is for my content to show when the button is clicked and hide when anywhere on the body is clicked. However, it seems that Angul ...

Struggling with passing data to the API controller in Laravel when attempting to override sendResetLinkEmail with Vue and Vuex integrated

I'm currently working on implementing the forgot password feature for my web application using Laravel along with Vue and Vuex. I came across a helpful tutorial at . I tried to integrate Vuex into this tutorial, but unfortunately, it didn't work ...

In JavaScript, what do we call the paradigm where a variable equals a variable equals a function? Let's take

Feeling a bit overloaded at the moment, so forgive me if this question seems too simple. I managed to accidentally write some code in Jest for testing a Vue application that actually works: const updateMethod = wrapper.vm.updateMethod = jest.fn() expect(u ...

Preventing text from wrapping in a TypeScript-generated form: Tips and tricks

I’m currently working on a ReactJS project and my objective is simple: I want all three <FormItem> components to be displayed in a single line without wrapping. However, I am facing the following output: https://i.stack.imgur.com/mxiIE.png Within ...

Retrieving values with Jquery on a function's onClick event

Here is a small script that retrieves values from a select element <script> jQuery(document).ready(function() { var selectedValue = jQuery("#tr_val").val(); }); </script> When you click on this div and execute the open_win function, I need t ...

Retrieving Data from Vue JS Store

I am fetching value from the store import {store} from '../../store/store' Here is the Variable:- let Data = { textType: '', textData: null }; Upon using console.log(store.state.testData) We see the following result in the cons ...

The CSS transition duration is not being applied properly on the initial transition effect

Looking to create a dynamic set of sliding divs that can be triggered with the press of a button. Each div will contain a thumbnail image and accompanying text. The goal is to enable the user to navigate through the content by clicking the left or right bu ...