假設vue實例中data有msg屬性,我們就可以同this.msg來獲取該值。
普通函數的this指向vue實例,可以獲取到對應的值
箭頭函數的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">獲取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>
