You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Vue Composition API中使用Buefy Toast?解决$buefy未定义报错

在Buefy的Composition API中调用Toast通知的解决方案

问题核心:Composition API的setup函数没有Options API中的this上下文,直接使用this.$buefy会触发Cannot read properties of undefined (reading '$buefy')错误。

以下是两种可行的解决方法:

方法一:使用inject获取Buefy实例(推荐)

通过Vue的inject方法直接获取Buefy注入的全局实例,这是官方推荐的规范用法:

<b-button type="is-info is-light" @click="toast">Click to show</b-button>
<script>
import { inject } from 'vue'

export default {
  setup() {
    const $buefy = inject('$buefy')

    const toast = () => {
      $buefy.toast.open('Something happened')
      // 也可以传入配置项自定义Toast
      // $buefy.toast.open({
      //   message: '操作成功',
      //   type: 'is-success',
      //   position: 'is-top-right',
      //   duration: 4000
      // })
    }

    return { toast }
  }
}
</script>

方法二:通过getCurrentInstance访问全局属性

如果场景需要,也可以通过getCurrentInstance获取当前组件实例,进而访问全局的$buefy属性:

<b-button type="is-info is-light" @click="toast">Click to show</b-button>
<script>
import { getCurrentInstance } from 'vue'

export default {
  setup() {
    const instance = getCurrentInstance()
    const $buefy = instance.appContext.config.globalProperties.$buefy

    const toast = () => {
      $buefy.toast.open('Something happened')
    }

    return { toast }
  }
}
</script>

注意:getCurrentInstance主要用于Vue内部或库开发,生产环境下可能因打包优化导致无法正常获取实例,优先使用方法一。

内容的提问来源于stack exchange,提问作者milad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 03:12:58