[英]Define global variables to use inside components
I have a Laravel 8 project, with vue-sweetalert2 installed.我有一个 Laravel 8 项目,安装了 vue-sweetalert2。 I'd like to define the Toast behaviour once, and then call it inside my components.
我想定义一次 Toast 行为,然后在我的组件中调用它。
By now I have this code:现在我有这个代码:
/js/components/Mypage.vue /js/components/Mypage.vue
<script>
export default {
data: function () {
return { ... };
},
mounted() { ... },
methods: {
myMethod: function () {
const Toast = this.$swal.mixin({
toast: true,
showConfirmButton: false,
timer: 2000,
timerProgressBar: false,
});
axios
.post("/api/something")
.then((res) => {
Toast.fire({
icon: "success",
title: "Tessera rinnovata",
});
});
...
</script>
This works fine, of course, but as you can see Toast is defined inside the method, and I cannot re-use it somewhere else.当然,这很好用,但正如您所见,Toast 是在方法内部定义的,我不能在其他地方重用它。
I'd like to define it inside app.js (maybe) and than access it everywhere, but if I move the code inside app.js as is, I receive an error, that tells me that $swal is not defined.我想在 app.js 中定义它(也许),而不是在任何地方访问它,但是如果我按原样移动 app.js 中的代码,我会收到一个错误,告诉我 $swal 没有定义。 I tried to use Swal instead of $swal... nothing changed.
我尝试使用 Swal 而不是 $swal... 没有任何改变。
/js/app.js /js/app.js
import VueSweetalert2 from "vue-sweetalert2";
import "sweetalert2/dist/sweetalert2.min.css";
window.Vue = require("vue").default;
import VueRouter from "vue-router";
Vue.use(VueRouter);
Vue.use(VueSweetalert2);
const Toast = $swal.mixin({
toast: true,
showConfirmButton: false,
timer: 2000,
timerProgressBar: false,
});
So, how can I define the Toast once?那么,如何定义 Toast 一次呢?
It looks like you're trying to setup the SweetAlert instance ( this.$swal
in your components) with initialization options.看起来您正在尝试使用初始化选项设置 SweetAlert 实例(组件中的
this.$swal
)。 That could be done when installing the vue-sweetalert
plugin.这可以在安装
vue-sweetalert
插件时完成。 The second argument to Vue.use()
is for the plugin options: Vue.use()
的第二个参数是插件选项:
// js/app.js
import Vue from 'vue'
import VueSweetAlert from 'vue-sweetalert2'
Vue.use(VueSweetAlert, {
toast: true,
showConfirmButton: false,
timer: 2000,
timerProgressBar: false,
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.