【问题标题】:How to implement vue package如何实现vue包
【发布时间】:2020-01-29 07:06:23
【问题描述】:

Vue 中的新功能并尝试使用名为 vue-toastr 的插件。 尝试与 Laravel 和 Vue 一起使用已经设置好了。 但是,我收到一条错误消息,提示“TypeError:无法读取未定义的属性 '$toastr'”。 我是 Vue 的新手,很难弄清楚我做错了什么。

我采取的步骤。 通过 npm 安装插件。

app.js

require('./bootstrap');

import VueToastr from "vue-toastr";

window.Vue = require('vue');
Vue.use(VueToastr, {});

Vue.component('new-question', require('./components/questions/NewQuestion.vue').default);

const app = new Vue({
    el: '#app',
});

下面是我的 Vue 组件的 JS 部分。

<script>
    import VueToastr from "vue-toastr";

    export default {
        props: [
            'route',
            'method'
        ],
        components: {
            VueToastr
        },
        data(){
            return {
                // Initialized to zero to begin
                form: {},
            }
        },
        mounted() {

        },
        methods: {
            formSubmit: function(){
                console.log('form submit');
                axios({
                    method: this.method,
                    url : this.route,
                    data : this.form
                }).then(function (response) {
                    console.log(response);
                    this.$toastr.s("ssss");
                    //this.VueToastr.s("ssss");
                }).catch(function (error) {
                    console.log(error);
                });
            }
        }

    }
</script>

非常感谢任何帮助

【问题讨论】:

    标签: javascript vue.js vuejs2


    【解决方案1】:

    替换为这个(添加var self = this;):

    formSubmit: function(){
        console.log('form submit');
    
        var self = this;        
    
        axios({
            method: this.method,
            url : this.route,
            data : this.form
        }).then(function (response) {
            console.log(response);
            self.$toastr.s("ssss");
            //this.VueToastr.s("ssss");
        }).catch(function (error) {
            console.log(error);
        });
    }
    

    更新。

    另外,你可以像这样使用箭头函数作为回调:

    formSubmit: function(){
        console.log('form submit');
        axios({
            method: this.method,
            url : this.route,
            data : this.form
        }).then((response) => {
            console.log(response);
            this.$toastr.s("ssss");
            //this.VueToastr.s("ssss");
        }).catch(function (error) {
            console.log(error);
        });
    }
    

    【讨论】:

    • 成功了。你能解释一下 var self = 这个吗?是否有某种文档可以阅读更多相关信息?
    • 当你进入另一个作用域比如匿名函数时,this 指向那个作用域(这里是匿名函数)。如果你还想访问父作用域(这里是 Vue 实例),你需要保存引用。这不是Vue中的技巧,而是JS中的常见技巧。
    • @ElaBuwa,我已经更新了关于使用箭头函数的答案。 thisthen 回调中有另一个上下文,因此您需要使用另一个(例如,self)变量来引用正确的(vue 对象)上下文。或者你可以使用箭头函数来代替它,虽然它没有与 this 的绑定。
    猜你喜欢
    • 1970-01-01
    • 2018-06-21
    • 2021-09-13
    • 1970-01-01
    • 2023-03-27
    • 2017-08-30
    • 1970-01-01
    • 1970-01-01
    • 2022-11-14
    相关资源
    最近更新 更多