Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
426 views
in Technique[技术] by (71.8m points)

vue组件内更新DOM绑定方法,this的指向竟然不是VueComponent对象?

组件代码如下,我在网页上触发更新后的add方法,打印出来的this竟然是window?

Vue.component('button-counter', {
        data: function() {
            return {
                count: 0,
                value: 1
            }
        },
        mounted() {
            let async = Promise.resolve();
            async.then(_ => {
                this.count++
                this.add = function() {
                    console.log(this)
                }
            })
        },
        methods: {
            add: function() {
                console.log(0)
            }
        },
        template: '<div><button v-on:click="add">You clicked me {{ count }} times.</button></div>'
    })

image


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
function() {
  console.log(this);
}
//函数会有作用域,可以使用箭头函数
() => { console.log(this); }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...