Programing

vue 클래스 구성 요소에서 $bvToast에 액세스하는 방법

c10106 2022. 4. 11. 20:44
반응형

vue 클래스 구성 요소에서 $bvToast에 액세스하는 방법

나는 vue.js를 처음 접하지만 몇 가지를 알아낼 수 있었다.나는 보통 j로 시작했지만 지금은 class style vue 컴포넌트가 있는 typecript로 바꾸었다.구성 요소 스타일링에는 bootstrap-vue를 사용한다.

main.ts 파일로 나는 bootstrap과 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')

스토어에서 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;
      }
  }
}

모든 게 잘 되는 거야알림을 생성하는 vue 구성 요소에서 이 스토어의 인스턴스를 가져올 수 있지만 다음 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는 나에게 다음과 같은 오류를 주지만.그러나 토스트는 생산되어 보여지지 않았다.

'$bvToast' 속성은 'UserNotification' 형식에 존재하지 않는다.베투르(2339년)

$bvToast를 다르게 통합하여 작동하는 TestView를 만들었다.

<template>
  <b-container fluid>
    <h1>This is the page for testing components and functionality</h1>
    <hr>
    <div>
      <h3>Trigger für 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>

내가 뭘 잘못하고 있는지 제안해 줄 수 있어?고마워

문제 해결 또는 개선

왜 그런지 모르겠지만 지금은 더 이상 변화 없이 작동해.미안하지만 난 이걸 더 이상 재현할 수 없어.또한 웹 콘솔도 오류를 표시하지 않는다.

그래서 UserNotification 구성 요소 내의 vue 인스턴스에 액세스할 수 있을 것 같다.UserNotification은 Vue를 확장하므로 VueX가 아닌 Vue 인스턴스다.답변에서 제외된 해답은 필요치 않았다.

Vetur만이 $vbToast를 UserNotification의 속성이거나 타이프스크립트 컨텍스트에서 확장된 Vue 인스턴스로 인식하지 못하는 것이 가능한가?

thisVueX의 컨텍스트는 Vue 인스턴스가 아니므로this.$bvToast직접 사용할 수 없음.

그러나 VueX 내의 기본 Vue 인스턴스에 액세스하는 방법이 있다.사용하다this._vm.$bvToast대신에

참조:

참조URL: https://stackoverflow.com/questions/59865660/how-to-access-bvtoast-in-vue-class-component

반응형