在vuepress中使用vue-toastification通知组件(踩坑日记)
本页信息
页面访问量
0
评论数量 0
本页链接 点击复制
在写完了vue中使用vue-toastification通知组件的教程后,我发现他也可以在vuepress-theme-hope中集成
安装
安装依赖
在项目根目录执行
npm
npm install --save vue-toastificationpnpm
pnpm install --save vue-toastificationyarn
yarn add vue-toastification在配置中启用
按照官方文档的说法,我们应该在自定义vue组件中直接引入vue-toastification组件(第一个坑),但是我们并没有main.js这样的入口文件,只能在~/.vuepress/client.js中注册组件
示例
.vuepress/client.js
import { defineClientConfig } from 'vuepress/client'
//...
import "vue-toastification/dist/index.css";
import Toast from 'vue-toastification'
export default defineClientConfig({
enhance({ app }) {
//其他内容
app.use(Toast, {
position: 'top-right',
timeout: 3000,
closeOnClick: true,
pauseOnFocusLoss: true,
pauseOnHover: true,
draggable: true,
draggablePercent: 0.6,
showCloseButtonOnHover: false,
hideProgressBar: false,
transition: 'Vue-Toastification__slideBlurred',
})
},
})配置vite预打包
如果只是在client.js中注册组件,编译的时候100%会报错(大坑)
就像这样
error
import Toast, { useToast } from "vue-toastification";
^^^^^^^^
SyntaxError: Named export 'useToast' not found. The requested module 'vue-toastification' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, for example using:
import pkg from 'vue-toastification';
const { useToast } = pkg;必须在~/.vuepress/config.js中配置vite预打包才能编译通过
.vuepress/config.js
import { viteBundler } from '@vuepress/bundler-vite'
import { defineUserConfig } from 'vuepress'
export default defineUserConfig({
//...
bundler: viteBundler({
viteOptions: {
optimizeDeps: {
include: ['vue-toastification'], // 开发依赖预打包
},
ssr: {
noExternal: ['vue-toastification'], // 对 SSR 也进行打包
},
},
}),
//...
})这样就可以像在普通vue项目里一样使用vue-toastification了
使用示例
编写任意组件
比如
example.vue
<script setup>
import { useToast } from 'vue-toastification'
const toast = useToast()
const showToast = (type, message) => {
toast[type](message)
}
</script>
<template>
<div style="display: flex;flex-direction: column;">
<span class="aaa" style="background-color: #4caf50;" @click="showToast('success', '这是一条成功消息')">
点击显示成功消息
</span>
<br />
<span class="aaa" style="background-color: #2196f3;" @click="showToast('info', '这是一条信息消息')">
点击显示信息消息
</span>
<br />
<span class="aaa" style="background-color: #ffc107ff;" @click="showToast('warning', '这是一条警告消息')">
点击显示警告消息
</span>
<br />
<span class="aaa" style="background-color: #ff5252;" @click="showToast('error', '这是一条错误消息')">
点击显示错误消息
</span>
</div>
</template>
<style scoped>
.aaa {
cursor: pointer;
color: #fff;
padding: 5px;
border-radius: 5px;
}
</style>在任意页面使用
example.md
<script setup>
import example from 'xxx/example.vue'
</script>
<example />或注册为全局组件
~/.vuepress/client.js
import example from 'xxx/example.vue'
import { defineClientConfig } from 'vuepress/client'
export default defineClientConfig({
enhance({ app }) {
app.use(example)
},
})相关链接
参考文献
更新日志
2026/3/29 04:07
查看所有更新日志
81544-新增了两篇博文,修改了一些文件于

