我正在创建一个 Laravel SPA,并使用 vue.js 作为框架。我在我的项目中添加了 sweetalert 包,但是每当我使用 toast
函数时,它都会出现错误。我尝试使用其他函数,例如 swal.fire
,除了 toast.fire
之外,它都可以工作。有人可以帮我弄这个吗?这是我的一些代码。
app.js
require('./bootstrap');
import Vue from 'vue'
import { Form, HasError, AlertError } from 'vform'
import moment from 'moment'
import VueRouter from 'vue-router'
import VueProgressBar from 'vue-progressbar'
import swal from 'sweetalert2'
window.Form = Form;
window.swal = swal;
window.toast = toast;
window.Vue = require('vue');
Vue.use(VueRouter)
Vue.component(HasError.name, HasError)
Vue.component(AlertError.name, AlertError)
const toast = swal.mixin({
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 3000
});
Vue.use(VueProgressBar, {
color: 'rgb(143, 255, 199)',
failedColor: 'red',
height: '2px'
})
const routes = [
{ path: '/dashboard', component: require('./components/Dashboard.vue').default },
{ path: '/profile', component: require('./components/Profile.vue').default},
{ path: '/users', component: require('./components/Users.vue').default}
]
const router = new VueRouter({
mode: 'history',
routes // short for `routes: routes`
})
Vue.filter('upText', function(text){
return text.charAt(0).toUpperCase() + text.slice(1);
});
Vue.filter('myDate', function(created){
return moment(created).format('MMMM Do YYYY');
});
Vue.component('dashboard', require('./components/Dashboard.vue').default);
Vue.component('profile', require('./components/Profile.vue').default);
Vue.component('users', require('./components/Users.vue').default);
const app = new Vue({
el: '#app',
router
});
用户.vue
<template>
//html codes
</template>
<script>
export default {
data(){
return{
users: {},
form: new Form({
name: '',
email: '',
password: '',
type: '',
bio: '',
photo: '',
})
}
},
methods: {
loadUsers(){
axios.get("api/user").then(( {data }) => (this.users = data.data));
},
createUser(){
this.$Progress.start();
this.form.post('api/user');
toast.fire({
type: 'success',
title: 'User Created',
position: 'top-end',
})
this.$Progress.finish();
}
},
created() {
console.log('Component mounted.');
this.loadUsers();
}
}
</script>
最佳答案
在该行运行时,toast
将为 undefined
:
window.toast = toast;
请注意,const toast = swal.mixin({
行稍后出现。您需要以相反的方式编写这些行。
就我个人而言,我一开始就不会直接在 window
上公开这些内容。根据需要导入它们或将它们添加到 Vue 原型(prototype)中:
Vue.prototype.$toast = toast
然后,您可以通过在组件中调用 this.$toast.fire
来使用它。
关于laravel - [Vue警告] : Error in v-on handler: "TypeError: Cannot read property ' fire' of undefined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57283630/