A guide on accessing $bvToast in Vue class components

I am fairly new to vue.js but I have managed to figure out some things. I initially started with regular js, but then transitioned to typescript with class style vue components. For styling the components, I rely on bootstrap-vue.

In my main.ts file, I imported bootstrap along with the vuex store

...
import BootstrapVue from 'bootstrap-vue'
//use custom bootstrap styling
import '../src/bootstrap/bootstrap.css'
import 'bootstrap-vue/dist/bootstrap-vue.css'
Vue.use(BootstrapVue)

...//some more code

new Vue({
 router,
 store,
 i18n,
 render: h => h(App)
}).$mount('#app')

Within the store, I dynamically register a NotificationModule

NotificationModule.ts

//import node modules
import { Module, VuexModule, Mutation, Action } from "vuex-module-decorators";
import { store } from "@/store";

//import application modules
import i18n from '@/i18n';

import Notification from '../types/Notification';
import Message from '../types/Message';
import logger from '@/system/logger';

@Module({
    dynamic: true,
    store: store,
    name: "notification",
    namespaced: true,
})
export default class NotifcationModule extends VuexModule {

  //notification types definition with according prompts
  notificationTypes: Array<string> = ['info', 'success', 'warning', 'danger'];

  //definition of the notification object
  notification: Notification = {
      variant: '',
      prompt: '',
      message: ''
  }

  /**
   * prove the supported notification types
   */
  get getSupportedNotificationTypes(): Array<string> {
      return this.notificationTypes;
  }

  /**
   * provide the notification
   */
  get getNotification(): Notification {
    return this.notification;
  }

  @Action
  notify(msg: Message){

    logger.warn(`called notify with [type:${msg.variant}]:[text:${msg.text}]`);

    if(msg.variant === undefined || !Array.from(this.notificationTypes).includes(msg.variant)){
      msg.variant = 'info';
    }

    //configure custom notification data
    const notification = {
        variant: msg.variant,
        prompt: i18n.t(`notify.${msg.variant}`),
        message: msg.text || 'No message provided.'
    }

    this.context.commit('setNotification', notification);
  }

  @Mutation
  public setNotification(data: Notification) {
      if (data) {
          this.notification = data;
      }
  }
}

Everything is working fine so far. I can retrieve an instance of this store in the vue-component responsible for producing notifications. However, I am encountering an issue when trying to create a toast in the subsequent vue component.

Notification.vue

<template>
  <b-container></b-container>
</template>

<script lang="ts">
import { Component, Vue, Watch } from 'vue-property-decorator';
import { getModule, VuexModule } from 'vuex-module-decorators';
import NotificationModule from '../../util-notification/components/NotificationModule';
import Notification from '../types/Notification';
import logger from '../../../system/logger';

@Component
export default class UserNotification extends Vue {

  //get the instance of the NotificationModule
  noticationInstance: NotificationModule = getModule(NotificationModule);

  //watch the property 'notification' - accessed via getter method
  @Watch('noticationInstance.getNotification')
  onPropertyChange(notification: Notification, oldValue: string) {
    logger.debug(`replaced [${JSON.stringify(oldValue)}] by [${JSON.stringify(notification)}]`);

    //create a toast
    this.$bvToast.toast(notification.message, {
      title: notification.prompt || 'Info',
      variant: notification.variant || 'warning',
      solid: true
    });


  }
}
</script>

Vetur gives me an error within this file, even though it compiles successfully. Unfortunately, no toasts are being produced or shown.

Property '$bvToast' does not exist on type 'UserNotification'.Vetur(2339)

While testing a different approach in the TestView where I integrated $bvToast differently, it works perfectly there.

<template>
  <b-container fluid>
    <h1>This is the page for testing components and functionality</h1>
    <hr>
    <div>
      <h3>Trigger for vuex notification test</h3>
      <b-button @click="$bvToast.show('example-toast')" class="mb-2">Default</b-button>
    </div>

    <b-toast id="example-toast" title="BootstrapVue" static no-auto-hide>
      Hello, world! This is a toast message.
    </b-toast>

  </b-container>
</template>

Any suggestions on what might be going wrong here? Thank you

Problem solved, everything's working now!

Surprisingly, it just started working without any further changes. Apologies, as I am unable to reproduce the issue anymore. Additionally, the web console shows no errors either.

It appears that I can access the vue instance within my UserNotification component. Since UserNotification extends Vue, it is a Vue instance and not VueX. The solution described in the answer turned out to be unnecessary.

Could it be possible that Vetur simply doesn't recognize $vbToast as a property of UserNotification or the extended Vue instance in the Typescript context?

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

Maintain the selected bootstrap tab even after the page is refreshed, even when the content is loaded dynamically

I am currently facing an issue with loading tabs using Angular. Whenever a tab is clicked, the id is saved to localStorage. Now, I want to programmatically click on the same tab using jQuery when the page refreshes. However, since the DOM element for the ...

The specified dependency, * core-js/fn/symbol, could not be located

I am in the process of developing a Vue.js application with Vuex and have encountered some errors during the build. I attempted to resolve the issue by installing npm install --save core-js/fn/symbol, but unfortunately, it did not work as expected. https:/ ...

Changing a numeric string into a number within an Angular 2 application

Looking for advice on comparing Angular 2 expressions. I have an array of data stored as numeric strings in my database and I need to convert them to numbers before applying a condition with ngClass for styling purposes. Any suggestions on how to perform ...

Converting objects into CSV format and exporting them using JavaScript

When exporting to CSV, large strings are causing other cells to be rewritten. See the screenshot for the result of the export here. For the code related to this issue, refer to this link. The question is how to prevent large string values in a cell from a ...

Encountering a problem while trying to pin a message on Discord

Whenever a message is pinned in discord, it causes the bot to crash with the following error (although it can recover with forever but that's beside the point). The pinned message can be of any type (regular or embed). if (!value) throw new RangeE ...

Ionic 3 Storage Timing Explained

I have a scenario where I am trying to load JSON data from storage and display it on the HTML template of my page. However, when I try to do this, I encounter errors suggesting that the information is not yet available upon entering the page. I'm sta ...

The bundle.js file encountered an issue while running UglifyJs, expecting a name

I have been attempting to utilize UglifyJS to compress/minimize my bundle.js file. However, when executing webpack -p, I encountered the following error message: ERROR in bundle.js from UglifyJs Name expected [bundle.js:105519,6] The line causing the iss ...

Utilizing Chart.js with Vue for dynamic time axis plots from JSON data through computed properties

Trying to generate a chart with a time axis in Vue using Chart.js has been a challenge. Initially, everything worked perfectly when the data was set directly in the Data object as shown below: chartData: { datasets: [ { backgroundC ...

billboard.js: The 'axis.x.type' property is conflicting with different data types in this context

axis: { x: { type: "category" } }, An issue has arisen: The different types of 'axis.x.type' are not compatible with each other. The value of 'string' cannot be assigned to '"category" | &qu ...

Having trouble triggering a click event on Ant Design menu button using jest and enzyme

Troubleshooting the simulation of a click event on the Menu component using Antd v4.3.1 Component: import React from 'react' import PropTypes from 'prop-types' import { Menu } from 'antd' import { SMALL_ICONS, PATHS } fro ...

What is the process for activating the currently active tab or link within the MDBNav component of MDBreact?

Here is the code snippet I am working with: import React from "react"; import { BrowserRouter } from 'react-router-dom'; import { MDBNav, MDBNavItem, MDBNavLink } from "mdbreact"; const CustomTabs = props => { return ( <BrowserRouter& ...

Achieving asynchronous results in the parent function with TypeScript: a guide

The code structure provided is as follows: import {socket} from './socket'; class A{ Execute(...args[]){ //logic with Promises SomeAsyncMethod1().then(fulfilled1); function fulfilled1(){ SomeAsyncMethod2(args).then(fulfilled2); ...

Updating the state of a React component through a button click using React-JS

In my React-JS project, I am using Semantic-ui to create form inputs and a submit button. These forms have a property called 'error', and the value of this property is determined by the state. The issue arises when I click on the 'Next&apos ...

Display items in a not predetermined order

Despite its simplicity, I am struggling to get this working. My aim is to create a quiz program using JavaScript. Here is the basic structure: <ul> <li>option1</li> <li>option2</li> <li>option3</li> </ul> &l ...

I'm looking for a way to create a Redux thunk action creator that will return a promise. How

In my code, I have a primary thunk that is triggered by a button click. Within this thunk, I need to invoke another thunk and ensure it completes before proceeding. The second thunk returns a promise. Below is an excerpt of the code in question: export f ...

Storing data retrieved from an asynchronous call in AngularJS to a variable

Here is the code where I am attempting to utilize promise to store data from an asynchronous call in a variable, but it's not functioning as expected. I am relatively new to promises and after some research, I learned that promises can be helpful in s ...

Error Received While Attempting to Log in using Ajax

Having an issue with logging in using ajax and php. I am able to log in successfully, but when trying to display an alert message and refresh the page upon login, it gives me an error without refreshing. However, upon manually refreshing the page, I can se ...

Adding an AngularJS directive dynamically that utilizes a $http request for fetching data

Currently facing an intriguing issue, I am attempting to create something like this: input key 1 , input value 1 input key 2 , input value 2 < button to add more > < submit button > Essentially, a user can click submit and send a Get req ...

Oops! SAPUI5 is encountering an issue with reading property '0' of undefined

Is there a possibility of encountering multiple errors leading to this specific error message? https://i.stack.imgur.com/RpWhw.png Despite searching online, it appears that the error occurs in the JavaScript file when getelementbyid returns null. However ...

How can I retrieve data from the Hasura hook "useQuery"?

As a newcomer to web development, I am attempting a simple 'GET' request using the "useQuery" hook from Hasura. However, I am encountering difficulties accessing my data. Strangely, the query has been successfully tested on the Hasura console wit ...