vue+jquery 作用域問題

先上代碼

var app = new Vue({
        el: '#app',
        data: {
            inputable: true,
            canclick: true,
            reply: false,
            name: '',
            email: '',
            content: ''
        },
        methods: {
            sendmsg: function() {
                $.ajax({
                    url: '001.php',
                    type: "POST",
                    dataType: 'json',
                    data: {
                        time: $('#time').val(),
                        name: $('#name').val(),
                        email: $('#email').val(),
                        message: $('#message').val()
                    },
                    success: function(result) {
                        this.canclick = false
                        this.reply = true
                        this.inputable = false
                        console.log(this)
                        console.log("success", result);
                    },
                    error: function(result) {
                        alert('好像哪裡錯了, 請再試一次, 或是email給chienwei0526@gmail.com吧! 我會很謝謝你的')
                        console.log("error", result);
                    }
                })

            }
        },
        computed: ...略

各位大大, 我想請問要在jquery封裝好的ajax對象裡如果要調用外面vue的data值, 要如何調用? success函數裡的this好像是指向 $ajax 如果要指向new Vue 的data, 在ajax裡的success要如何寫呢?

我只想要在success的時候執行this.canclick = false,this.reply = true,this.inputable = false這三個動作, 不曉得有沒有辦法?

                    success: function(result) {
                        this.canclick = false
                        this.reply = true
                        this.inputable = false
                        console.log(this)
                        console.log("success", result);
                    },
阅读 2.9k
3 个回答

在$.ajax()外面把this 给保存下来 var _this = this

es6的箭头函数 sendmsg: (()=>{})

app.canclick = false,app.reply = true,app.inputable = false;这样应该可以(项目用script标签引用可以这样做,vue-cli搭建的工程,楼上的方法可以)
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题