vue中关于this的指向

假设vue实例中data有msg属性,我们就可以同this.msg来获取该值。

普通函数的this指向vue实例,可以获取到对应的值

箭头函数的this指向全局window,不能获取到该值

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