vue里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指向调用它的Vue实例,即(new Vue)
<div id="app">
<button class="btn btn-primary" @click="addFn">点击添加并查看this</button>
<ul class="list-group" v-for="item in list">
<li class="list-group-item">{{item}}</li>
</ul>
</div>
<script>
export default ({
data() {
return{
list: ["banner", "orange", "apple"]
},
}
methods: {
addFn() {
alert(this.list);
this.list.push("Potato")
}
})
</script>
实例:这里的this指向的是new Vue这个对象。new Vue也可以写成var Vue=new Vue({}).所以这里的this指向的是Vue。
但是在filters过滤属性里this的指向就成为了undefined
由此可见在filters里面不能直接调用this
当我们需要用到filters里的this时,我们可以把this作为参数传入,就可以达到我们需要的效果
<template>
<div class="department-container">
<div class="app-container">
<el-card>
<!-- 具体页面结构 -->
<div>{{ sum|screen(this) }}</div>
</el-card>
</div>
</div>
</template>
<script>
export default ({
filters: {
screen(value, that) {
console.log(value, '过滤的值为')
console.log(that.str, 'filters里的this指向') //这里调用之后打印的值为12
}
},
data() {
return {
sum: 1,
str: 12
}
}
})
</script>