1

使用 vue 资源将 vue 数据作为正文发布请求

<script>
    //var VueValidator = require ('vue-validator');
    new Vue({
        el: '#app',
        data: {
            email: '',
            password: '',
            _token: '{{csrf_token()}}',
            uid: '{{$row->id}}'
        },
        methods: {
            changeCredentials: function (e) {
                console.log(this.email); --> **RETURNS EMPTY**
                var resource = this.$resource('myurl/{id}');
                resource.save({id: this.uid}, {body: function () {
                    console.log(this.data);
                    return this.data;
                }}).then((response) => {
                    // success callback
                    console.log(response);
                }, (response) => {
                    // error callback
                });


                //alert('here');
            }
        }
    });
</script>

你能告诉我为什么 this.uid 有效但 this.email 无效吗?谢谢

4

1 回答 1

1

这是因为当您访问时,this.data您处于一个回调中,该回调会更改您当前所在的范围,this而实际上并不是您的 Vue 组件。

通过设置_this,您可以在范围更改并进入回调后访问该变量。

changeCredentials: function () {
    var resource = this.$resource('myurl/{id}');
    var _this = this;

    resource.save({id: _this.uid}, {body: function () {
        console.log(_this.data);

        return _this.data;
    }});
}
于 2016-09-01T08:02:21.383 回答