vue中关于this的指向


假设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>

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM