My goal is to manage components asynchronously in Nuxt.js while also showcasing alert messages

My Desired Outcome

I am hoping to implement a notification system that notifies the user based on the response from the server. However, since notifications are handled by a separate component, I need to asynchronously call this component in my code. The Vue.js documentation suggests using Vue.component, but how can I achieve this with Nuxt.js?

Code Snippet

In order to use search.vue within success.vue

search.vue

<template>
  <v-app>
    <div
      class="teal lighten-1 background pa-10"
    >
      <!-- <div
        v-if="responseBook === 200"
        > -->
      <alert-success />
      <v-sheet
        width="1100px"
        class="mx-auto pa-5 rounded-xl"
        color="grey lighten-5"
        min-height="500px"
      >
        <!-- Book search and display section -->
        <BookPostDialog />

        <!-- Display selected data here -->
        <BookPostSelected />
      </v-sheet>
    </div>
  </v-app>
</template>

<script>
export default {
  computed: {
    responseBook () {
      return this.$store.state.book.responseBook.status
    }
  }
}
</script>

<style lang="scss" scoped>
  .background {
    background-image: url('~/assets/images/tree.png');
    background-repeat: space repeat;
  }
</style>

Alert/success.vue

<template>
  <v-alert type="success">
    Request Successful!
  </v-alert>
</template>

Answer №1

If you're interested in utilizing that particular feature, it would be beneficial to search for a component like this one:
Alternatively, you can explore the plethora of CSS frameworks available as most likely each of them provides something similar.

Another option is to create it yourself using portals.
For Vue2, you can achieve this by following these steps:

<portal to="destination" :disabled="true">
  <p>
    Your content
  </p>
</portal>

Answer №2

To display the success.vue component after connecting to the server (fetching or posting data), you can utilize v-if like this:

search.vue

<template>
    <div>
        <p>search component</p>
        <div v-if="this.$store.state.book.responseBook == 'ok'">
            Data was received.
            <success />
        </div>
    </div>
</template>

<script>
export default {
    
    mounted() {
        this.$store.dispatch('getData')
    }

}
</script>

success.vue

<template>
    <div>
        success component
    </div>
</template>

Next, in your store/index.js file:

import Vuex from "vuex";

const createStore = () => {
    return new Vuex.Store({

state: {
            book: {
                responseBook: ""
            }
        },
        
mutations: {

            bookMutate(state, data) {
                state.book.responseBook = data;
            }
        },
actions: {       
getData(vuexContext) {
                let vue = this;
                // Your request logic goes here
                setTimeout(function() {

                    vue.$axios.$get("https://pokeapi.co/api/v2/pokemon/ditto").then((result) => {
                        console.log(result);
                        vuexContext.commit("bookMutate", "ok");
                    }).catch(err => {
                        console.log(err);
                    })

                }, 10000)

            },
}
        
        });
};

export default createStore;

I deliberately used setTimeout() in my action to ensure that the success component loads after receiving the data. In a real scenario, it is recommended to use this action instead:

getData(vuexContext) {
                               this.$axios.$get("https://pokeapi.co/api/v2/pokemon/ditto").then((result) => {
                    console.log(result);
                    vuexContext.commit("bookMutate", "ok");
                }).catch(err => {
                    console.log(err);
                })

 },

I utilized axios for API calls, but feel free to use your preferred method for fetching data. However, remember to commit the mutation to alter the state.

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

What can be used instead of makeStyles in Material UI version 5?

My journey with Material UI version 5 has just begun. In the past, I would utilize makestyles to incorporate my custom theme's styles; however, it appears that this method no longer works in v.5. Instead of relying on {createMuiTheme}, I have shifted ...

Guide for dynamically populating Jqgrid Dropdown depending on another dropdown's data选择如何根

On my screen, I have two dropdowns. One is a standard Razor dropdown and the other is a Jqgrid dropdown. The code for the Razor dropdown looks like this: <div class="col-md-4"> <label for="" class="control-label">Loan Currency</ ...

An unusual problem encountered with JSON and PHP

Is there a specific reason why a JSON string fails to be evaluated (transport.responseText.evalJSON();) on the server but works fine on my local setup? I'm making a simple AJAX request like this: new Ajax.Request( this.saveUrl, { ...

Error: Attempting to access property 'propeller' of an undefined object has caused a TypeError

I am working on a tutorial that can be found at this link: https://tympanus.net/codrops/2016/04/26/the-aviator-animating-basic-3d-scene-threejs/ During the process, I encountered an error message: Uncaught TypeError: Cannot read property 'propeller& ...

Identify the location of the mouse and activate a specific function based

Tracking the x-coordinate of the mouse is crucial in this scenario. When the mouse approaches a specific threshold (250px) towards the left edge of the window, it should trigger the function "openNav." The function should close when the mouse moves away fr ...

Fill out FormBuilder using data from a service within Angular2

I am working with an Angular2 model that I'm filling with data from a service. My goal is to use this model to update a form (created using FormBuilder) so that users can easily edit the information. Although my current approach works, I encounter er ...

The function does not have a specified return value

I've been grappling with this issue for quite some time and I can't figure out what's causing the problem. In my code, I have a separate class called Database.js that handles MySQL functions, manages connections, queries, etc. My goal is to ...

Encountering a syntax error with the AngularJS ng-class expression

While navigating through a tutorial application designed for use with the Ionic platform, which is based on angular 1.2.4, I encountered a perplexing error in this Angular markup: <content has-header="true" scroll="false"> <list> ...

Setting up a service in angularjs that is reliant on another service

One thing I'm trying to figure out is how to utilize a service like $http outside of the $get function. Is this even possible? Currently, my code loads a json file that contains a dictionary used by my application in various ways. I want users to have ...

Unable to locate module - relative file path

I'm currently running a test with the following code and encountering an error message: Failed: cannot find module '../page/home_page.js The main page consists of: describe("login to website",function(){ var employeeId; var employee ...

What is the best way to conceal an element when another element is given a specific class?

Imagine you have 2 buttons The first button <button class="arguments variation-one">Some text</button> - this button has dynamic classes like: variation-one, variation-two, variation-three, but the .arguments class remains static. a ...

Load subtitles into your video in real-time

Let's discuss the scenario: The server is receiving a stream of SRT file. This stream is then converted into VTT format by the server, which is further buffered and sent to the client through an io.socket connection. Below is the server-side code: s ...

Post-render for HTML linkage

Is there a method to execute customized code after Knockout has inserted the html into the DOM and completed rendering? This is required in order to bind a nested view model to dynamically generated html code. Perhaps like this: <div data-bind="html: ...

Angular foreach method encounters a syntax issue

When I use the getTotal.getValues() function to make a server call that returns values like "one", "two", "three" up to "nine", I am able to print them using console.log(res). However, I am facing an issue where I cannot push these returned values into t ...

Difficulty building due to uppercase import in NPM dependency

While working on my Angular project, I encountered a dependency that uses Upper Camel Case import. from "./CSSToMatrix" export { parse, parseMat, toMat, getDistElementMatrix, caculateMatrixDist, getElementMatrix, createMatrix, } from "./C ...

Steps to invoke a function to add an element into a list

Every time a user clicks on a button, I want to generate a new tab. In this tab, when the user clicks again, I want a function to be called like: onclick('+reportname+','+report type+') onclick("'+reportname+'","'+repor ...

Compress a file using Maven and save it to a non-Java application folder

Is it feasible to implement versioning for zipped files of VUE.js applications in a Jenkins pipeline using Maven, even though they are not Java apps? I have successfully done this for other apps with Java using Maven, POM, Maven-Metadata-Plugin, Jenkins, a ...

Express: adding a question mark to the URL when submitting the form

Upon submitting a form with a "?" in the URL, I noticed that when posting it redirects me to the page and still returns a "?" in the URL. Directory: server.js, index.html, package.json, package-lock, src/models/form.js server.js: const express = require( ...

What is the best way to retrieve a MariaDB query result using Node.js?

I've been delving into the world of Node.js to enhance my web development skills, particularly in retrieving data from a mariaDB using SELECT queries and converting it into JSON for client requests. Despite scouring the internet and stackoverflow, I h ...

How to display a three.js scene in the center of a container

I'm having trouble getting my three.js scene to display above some cards and right below my navigation bar. Currently, the scene is rendering under the cards and is not centered. Despite looking at other forum posts for help, I can't seem to figu ...