美文网首页Vue学习
Vue中this指向的问题

Vue中this指向的问题

作者: 椰果粒 | 来源:发表于2018-08-01 20:49 被阅读12次

我们知道,如果Vue的data中有属性message,那么方法中直接用this.message就可以获取到这个message的值

在下面的例子中可以看出,普通函数的this指向的就是Vue的实例,this.message可以获取到data中的值,而箭头函数的this指向了window,不能获取到值

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="https://unpkg.com/vue@2.5.16/dist/vue.js"></script>
</head>
<body>
    <div id="app">
       <button v-on:click="getMessage">获取message的值</button> 
    </div>
    <script>
        new Vue({
            el : '#app',
            data : {
                message : "hello vue!"
            },
            methods : {
                // 箭头函数的this指向了window,其实应该指向vue的实例
                // 普通函数
                getMessage : function(){
                    // alert(this.message);
                    console.log(this);  // 指向Vue的实例
                },
                // 箭头函数
                getMessage : ()=>{
                    console.log(this);  // window
                }
            }
        })
    </script>
</body>
</html>

相关文章

  • vue中this指向问题

    根据VUE官方文档给出的解释 在Vue所有的生命周期钩子方法(如created,mounted,updated以及...

  • Vue中this指向的问题

    我们知道,如果Vue的data中有属性message,那么方法中直接用this.message就可以获取到这个me...

  • vue中this的指向问题

    在函数中需要遍历数组等对象时,遍历中的this会指向window,所以需要在遍历前定义一下this指向

  • vue中的this指向问题

    第一个输出英文"Hello!”,第二个输出中文“你好!”。这说明了showMessage1()里的this指的是w...

  • Vue中this使用的注意事项

    一、 axios中this的指向问题 在vue中使用axios做网络请求的时候,会遇到this不指向vue,而为u...

  • axios 在vue中this指向问题

    在Vue中this始终指向Vue,但axios中this为undefined,例如 若需要赋值给变量用以渲染数据,...

  • Vue笔记 -- axios中this的指向问题

    axios中this的指向问题

  • Vue常见错误

    1 this指向 vue中this指向的vm实例,如果map或者filter循环中,this的指向就是个迷了 解决...

  • vue中this指向小记

    普通函数中的的this指向取决于运行该函数的作用域,而箭头函数的this是定义时就固定了。然而在vue中有一事不明...

  • 为什么vue要使用 let that = this

    在Vue中this始终指向Vue,但一些其他组件如axios中this为undefined,通过let that ...

网友评论

    本文标题:Vue中this指向的问题

    本文链接:https://www.haomeiwen.com/subject/mffdvftx.html