Vue 中如何正确 定义 this 指向?

问题描述

Vue created 中定义 self = this 指向当前 vue 实例,但是在 methods 中使用 self 不能正确的指向当前实例。

相关代码

new Vue({
    el: '#vue',
    data: {
        col: 'dd'
    },
    created: function () {
        self = this
    },
    methods: {
        render: function() {
            jQuery.get(ajaxurl, function (res) {
                self.dd = 'ee'
            })
        }
    }
})

其中 self.dd 虽然可以正确的改变 data中 col 的值

但是如果此时页面有另一个 new Vue({}),刚好里边 data 中也有一个 col: 'dd'
这个时候 self.dd 就不能正确的指向当前 vue 实例了。
阅读 9.4k
3 个回答

在严格模式下,是不推荐这种全局变量的方式的,如果你想这么写 我猜可以

var instance=new Vue({
    el: '#vue',
    data: {
        col: 'dd'
    },
    created: function () {
        instance= this
    },
    methods: {
        render: function() {
            jQuery.get(ajaxurl, function (res) {
                instance.dd = 'ee'
            })
        }
    }
})

看你的这种开发方式,应该是直接写js的,但比较推荐的做法是用vue的cli构造出的.vue文件文件里开发,

vuemethods 中的 this 默认是自动执行 vue 实例的,所以同样的逻辑,在 methods 中也声明一个 self 变量储存 this 即可。

都8012年了,为啥不用箭头函数呀。

推荐问题