Here are my configuration and stpes.
1- from terminal
npm install sweetalert2
2- in main.js
import Swal from 'sweetalert2'
window.swal = Swal;
Vue.use(Swal);
// Toast config
const toast = Swal.mixin({
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 3000,
timerProgressBar: true,
onOpen: (toast) => {
toast.addEventListener('mouseenter', Swal.stopTimer)
toast.addEventListener('mouseleave', Swal.resumeTimer)
}
});
window.toast = toast;
3- usage in views
toast.fire({
icon: 'success',
title: 'Record has been updated.'
})
Errors/Problem:
237:5 error 'toast' is not defined no-undef
Instead of const toast use window.toast.
Related
I've installed the Storybook Js addon, "storybook-dark-mode-vue" (I'm not sure if it makes any difference whether or not I just used the default "storybook-dark-mode" addon) but I'm not sure how to trigger the "channels" from my vue component story.
My example story is:
import BToggle from './Toggle.vue';
export default {
name: 'Components/Toggle',
component: BToggle,
// More on argTypes: https://storybook.js.org/docs/vue/api/argtypes
parameters: {
docs: {
description: {
component: 'Nothing to see here',
},
},
},
argTypes: {
label: {
control: { type: 'text' },
},
onToggle: {
action: 'changed',
},
},
};
const Template = (args, { argTypes }) => ({
components: { BToggle },
props: Object.keys(argTypes),
template: '<b-toggle v-bind="$props" #onToggle="onToggle"></b-toggle>',
});
export const Default = Template.bind({});
Default.args = {
label: 'default',
};
The "onToggle" event works, I see the action being triggered in the Storybook "actions" tag, so how do I make it trigger the Storybook "STORYBOOK_DARK_MODE_VUE" event in my preview.js file?
My preview.js file has:
const channel = addons.getChannel();
channel.on('STORYBOOK_DARK_MODE_VUE', () => {
console.log('activating dark mode');
});
channel.off('STORYBOOK_DARK_MODE_VUE', () => {
console.log('activating dark mode');
});
Using Vite to build the app, I am getting the following error inside Electron:
index.c160f204.js:9 DOMException: Failed to execute 'querySelector' on 'Document': 'link[href="/C:UsersrankDocumentsSchoolCheckInElectronReaderdist/assets/Home.b0f26e4d.js"]' is not a valid selector.
It appears to me that the path inside the built code has the slashes removed, but I have no idea on how to solve that since it's generated code.
Using Node 17.9.0 on Windows 11 10.0.22000 Build 22000
Electron main.js:
const { app, BrowserWindow } = require("electron");
const path = require("path");
function createWindow() {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, "preload.js"),
},
});
win.loadFile("dist/index.html");
}
app.whenReady().then(() => {
createWindow();
app.on("activate", () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
});
app.on("window-all-closed", () => {
if (process.platform !== "darwin") {
app.quit();
}
});
Electron preload.js:
window.addEventListener("DOMContentLoaded", () => {
const replaceText = (selector, text) => {
const element = document.getElementById(selector);
if (element) element.innerText = text;
};
for (const type of ["chrome", "node", "electron"]) {
replaceText(`${type}-version`, process.versions[type]);
}
});
Vite.config.ts:
import { defineConfig } from 'vite'
import vue from '#vitejs/plugin-vue'
import * as path from "path";
// https://vitejs.dev/config/
export default defineConfig({
base: path.resolve(__dirname, './dist'),
plugins: [
vue(),
],
})
Using vue-tsc --noEmit && vite build to build and electron . to start.
If you copy/paste the faulty code into a browser console, you will notice a non UTF-8 character in your link, between Users and rank.
Get rid of it and it should work.
The simplest way to fix this would be to move the project to a path which doesn't contain weird chars (e.g: C:/projects/)
I was learning Vue 3 and get some trouble to use SweetAlert2 in app.js.
everything is ok and worked when i use SweetAlert2 in component Vue but not work in app.js
my goal:
i want to show alert with confirm button when get error response Unauthenticated. from axios interceptors and redirect user to login page
app.js
import {createApp} from 'vue'
require('./bootstrap')
import App from './App.vue'
import axios from 'axios'
import router from './router'
import store from './store'
// SweetAlert2
import VueSweetalert2 from 'vue-sweetalert2';
import 'sweetalert2/dist/sweetalert2.min.css';
axios.interceptors.response.use(function (response) {
return response
}, function (error) {
console.log(error.response.data.message)
if (error.response.data.message === 'Unauthenticated.') {
swal({
title: "Session Expired",
text: "Your session has expired. Would you like to be redirected to the login page?",
icon: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes",
closeOnConfirm: false
}).then((result) => {
if (result.value) {
window.location.href = "/login"
}
});
}
return Promise.reject(error)
})
const app = createApp(App)
app.config.globalProperties.$axios = axios;
app.use(router)
app.use(VueSweetalert2)
app.use(store)
app.mount('#app')
it work when i change error response with this, (but not elegant like this for me)
...
axios.interceptors.response.use(function (response) {
return response
}, function (error) {
console.log(error.response.data.message)
if (error.response.data.message === 'Unauthenticated.') {
alert('Session Expired');
window.location.href = "/login"
}
return Promise.reject(error)
})
...
i think it would be good if using sweetalert,
thank youu...
Explanation
I faced the same problem when using Vue 3, and I wanted to use sweetalert2 in my router/index.js to add an alert when a user goes to an unauthorized route.
The same problem will appear if you want to use a sweetalert2 in store/index.js after calling an action fetching data from the backend.
To work around this problem, you must use the native package of sweetalert2, then you can use swal in any .js file.
By the way, I don't want to install any external package, so I found that when you are installing the vue-sweetalert2, the native package will be installed also (because it is a dependency of vue-sweetalert2).
Workaround
All you have to do is:
Keep what you had done in main.js (to use sweetalert2 inside components).
In any .js file where you want to use swal, add this import Swal from 'sweetalert2/dist/sweetalert2', and now you can access and use Swal.fire({}).
Example
I will attach an example of what I want to do (in my case), and how I work around the problem:
My main.js file:
import { createApp } from 'vue';
import App from './App.vue';
import store from './store';
import router from './router';
import VueSweetalert2 from 'vue-sweetalert2';
import 'sweetalert2/dist/sweetalert2.min.css';
const app = createApp(App);
app.use(store);
app.use(router);
app.use(VueSweetalert2);
app.mount('#app');
My router/index.js
import { createRouter, createWebHistory } from 'vue-router';
import Swal from 'sweetalert2/dist/sweetalert2';
import store from '../store/index';
const router = createRouter({
routes: [
// ...
],
});
router.beforeEach((to, from, next) => {
if (to.matched.some((record) => record.meta['requiresAuth']) && store.state.auth.isAuthenticated === false) {
Swal.fire({
toast: true,
position: 'bottom-end',
showConfirmButton: false,
timer: 3000,
timerProgressBar: true,
icon: 'error',
title: 'Permission denied',
text: 'You are not authenticated to access this page.'
});
next({
name: 'login',
params: { nextUrl: to.fullPath }
});
}
next();
});
export default router;
i think you need to try withoud condition first,
try only sweet alert without :
axios.interceptors.response.use(function (response) {
return response
}, function (error) {
console.log(error.response.data.message)
if (error.response.data.message === 'Unauthenticated.') {
swal({
title: "Session Expired",
text: "Your session has expired. Would you like to be redirected to the login page?",
icon: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes",
closeOnConfirm: false
}).then((result) => {
if (result.value) {
window.location.href = "/login"
}
});
}
return Promise.reject(error)
})
u can try
https://www.npmjs.com/package/vue-sweetalert2
I'm trying to use vue router with an application on an Electron JS. If I use a router on the render page, then the router work done. But I do not understand how to make the transition to the page, for example,- 'Settings' using the Tray. At attempt of transition the empty page opens.
I have prepared a working example of the project. This problem exists only build project. In development mode all work well.
This is my work example on github. Please need help.
git clone https://github.com/DmtryJS/electron-vue-example.git
cd electron-vue-example
npm install
npm run build
and run dist\win-unpacked\example_for_stackoverflow.exe
my main.js file
'use strict'
import { app, protocol, BrowserWindow, Menu, ipcMain, Tray } from 'electron'
import { format as formatUrl } from 'url'
const electron = require('electron');
const path = require('path');
const isDevelopment = process.env.NODE_ENV !== 'production';
let imgBasePath;
if(isDevelopment) {
imgBasePath = path.join('src','assets', 'img');
} else {
imgBasePath = path.join(path.dirname(__dirname), 'extraResources', 'img');
}
let win;
let tray;
protocol.registerStandardSchemes(['app'], { secure: true })
const trayIcon = path.join(__static, 'img', 'icon.png');
function createWindow () {
win = new BrowserWindow({
width: 800,
height: 600,
icon: trayIcon
})
routeTo(win, "")
win.on('closed', () => {
win = null
})
//убрать меню
win.setMenuBarVisibility(true)
win.on('show', function() {
tray.setHighlightMode('always')
})
win.on('hide', function() {
tray.setHighlightMode('never')
})
}
// Quit when all windows are closed.
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
if (win === null) {
createWindow()
}
})
app.on('ready', () => {
createWindow()
win.webContents.openDevTools(); //открыть dev tools
createTray()
})
// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
if (process.platform === 'win32') {
process.on('message', data => {
if (data === 'graceful-exit') {
app.quit()
}
})
} else {
process.on('SIGTERM', () => {
app.quit()
})
}
}
function createTray()
{
let traiIconPath = path.join(imgBasePath, 'preloader_tray_icon.png')
tray = new Tray(traiIconPath)
const contextMenu = Menu.buildFromTemplate(
[
{
label: 'Settings',
type: 'normal',
click: function()
{
routeTo(win, "/settings")
let contents = win.webContents
contents.on('dom-ready', function()
{
if(!win.isVisible())
{
showWindow()
}
})
}
},
{
label: 'Exit',
type: 'normal',
click: function()
{
win = null
app.quit()
}
}
])
tray.setContextMenu(contextMenu)
tray.on('click', function() {
toggleWindow();
})
}
function showWindow() {
var position = getPosition();
win.setPosition(position.x, position.y, false)
win.show()
win.focus()
}
ipcMain.on('routerEvent', function(event, arg) {
routeTo(win, arg)
})
function routeTo(win, to) {
if (isDevelopment) {
win.loadURL(`http://localhost:${process.env.ELECTRON_WEBPACK_WDS_PORT}` + to)
} else {
win.loadURL(formatUrl({
pathname: path.join(__dirname, 'index.html' + to);,
protocol: 'file',
slashes: true
}))
}
}
And
router.js
import Vue from 'vue'
import Router from 'vue-router'
import Main from './../views/Main.vue'
import Settings from './../views/Settings.vue'
Vue.use(Router)
export default new Router({
//mode: 'history',
routes: [
{
path: '/',
name: 'home',
component: Main
},
{
path: '/settings',
name: 'settings',
component: Settings
}
]
})
You need to add created to the main Vue app check docs
// src/main.js
new Vue({
router,
render: h => h(App),
created() {
// Prevent blank screen in Electron builds
this.$router.push('/')
}
}).$mount('#app')
The solution for me was to remove the history mode in the vue router.
Sorry, but after one day of googling, I just found a solution. The case turned out to be
win.loadURL(formatUrl({
pathname: path.join(__dirname, 'index.html' + to);,
protocol: 'file',
slashes: true
}))
I delete formaUrl and everything works well
win.loadURL(path.join(__dirname, 'index.html' + to));
For me solution was this:
Check if app is running at addresses like this:
Local: http://x86_64-apple-darwin13.4.0:8080/
Network: http://localhost:8080/
Check if you can access x86_64..url in browser. If you are not seeing a webpage but can see it from localhost, then map 127.0.0.1 to x86_64-apple-darwin13.4.0 in hosts file. in mac its located in /etc/hosts in windows its in system32/drivers/etc.
I am creating my first nuxtjs project and am using the axios module as my HTTP client.
The Problem
Use the sweetalert2 plugin within the axios module's errorHandler.
nuxt.config.js
module.exports = {
modules: [
'#nuxtjs/axios'
],
axios: {
errorHandler (error) {
if (process.browser) {
const swal = require('sweetalert2')
swal({
title: 'Error',
text: 'Error',
confirmButtonColor: "#895CF2",
confirmButtonText: 'Zurück',
type: 'error'
}).then(function () {
window.history.back();
})
}
},
plugins: [
{ src: '~/plugins/sweetalert2', ssr: false }
],
build: {
vendor: ['axios', 'sweetalert2']
}
}
plugins/sweetalert2.js
import Vue from 'vue'
import swal from 'sweetalert2'
Vue.use(swal)
The errorHandler works without sweetalert and the sweetalert code works, as is in the frontend (pages/components).
I would be very thankful for any kind of help!