前端学习(2485):vue里面的this指向
一、普通函數(shù)中的this?
?
這是vue文檔里的原話:
All?lifecycle?hooks?are?called?with?their?'this'?context?pointing?to?the?Vue?instance?invoking?it.
意思是:在Vue所有的生命周期鉤子方法(如created,mounted,?updated以及destroyed)里使用this,this指向調(diào)用它的Vue實例,即(new Vue)。?
?<div id="app">
????<button class="btn btn-primary" v-on:click="on()">點擊添加并查看this</button>
????<ul class="list-group" v-for="item in list">
????????<li class="list-group-item">{{item}}</li>
????</ul>
</div>
<script>
????new Vue({
????????el: "#app",
????????data: {
????????????list: ["banner", "orange", "apple"]
????????},
????????methods: {
????????????on: function() {
????????????alert(this.list);
????????????this.list.push("Potato")
????????}
})
</script>
實例:這里的this指向的是new Vue這個對象。new Vue也可以寫成var C=new Vue({}).所以這里的this指向的是C。
?
?
二、箭頭函數(shù)中的this
箭頭函數(shù)沒有自己的this, 它的this是繼承而來; 默認(rèn)指向在定義它時所處的對象(宿主對象),而不是執(zhí)行時的對象, 定義它的時候,可能環(huán)境是window; 箭頭函數(shù)可以方便地讓我們在 setTimeout ,setInterval中方便的使用this。
這里箭頭函數(shù)指向window。
總結(jié)
以上是生活随笔為你收集整理的前端学习(2485):vue里面的this指向的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 前端学习(2025)vue之电商管理系统
- 下一篇: 前端学习(2197):__WEBPACK