【问题标题】:[Vue warn]: Error in v-on handler: "TypeError: Cannot read property 'fire' of undefined"[Vue 警告]:v-on 处理程序中的错误:“TypeError:无法读取未定义的属性 'fire'”
【发布时间】:2019-12-08 13:15:21
【问题描述】:

我正在创建一个 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
});

Users.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>

【问题讨论】:

    标签: laravel vue.js vue-router sweetalert2


    【解决方案1】:

    在这条线运行时,toast 将是undefined

    window.toast = toast;
    

    请注意,const toast = swal.mixin({ 行稍后出现。你需要反过来写这些行。

    首先,我个人不会直接在window 上公开这些内容。根据需要导入它们或将它们添加到 Vue 原型中:

    Vue.prototype.$toast = toast
    

    然后,您可以通过在组件中调用 this.$toast.fire 来使用它。

    【讨论】:

    • 它得到了我和"ReferenceError: $this is not defined"先生的错误
    • @Vince 我已经更新了我的答案,使其更加明确。主要问题是这两行是错误的。您必须在 window.toast 行之前有 const toast 行。鉴于我提出了多项建议,我很难确切知道您试图得到该错误的原因。
    • 哦,我明白了,这就是我不断收到错误消息的原因。现在它起作用了!我只是将window.toast = toast 放在const toast 方法之后。非常感谢
    【解决方案2】:

    如果出现axios.post,您必须拨打toast.fire,如下所示,

    createUser(){
      this.$Progress.start();
      axios.post('api/user', this.form).then(response => {
         toast.fire({
         type: 'success',
         title: 'User Created',
         position: 'top-end',
        })
        this.$Progress.finish();
      }).catch(error => {
        this.$Progress.finish();
      });
    

    您可以处理成功和失败并分别显示 toast 消息 .then.catch 事件。 希望这会有所帮助。

    【讨论】:

    • 你没有在app.js中导入toast吗?
    • 是的,先生。我想通了。我应该把window.toast 放在const.toast 之后,就像@skirtle 说的那样。谢谢你的回答先生。
    • 很高兴听到这个消息。继续编码! :D