vue过滤器filters获取不到this对象的解决办法
问题:想在过滤器filters中使用this,可能需要data或者props的一个值作为过滤的条件,如果直接使用this是会报错的,因为this为undefined,那如何解决呢?下面列举几个解决办法一、使用computed<template>{{ '1558490001000' | formatDate }}</template><script>export
·
问题:想在过滤器filters中使用this,可能需要data或者props的一个值作为过滤的条件,如果直接使用this是会报错的,因为this为undefined,那如何解决呢?下面列举几个解决办法
一、使用computed
<template>
{{ '1558490001000' | formatDate }}
</template>
<script>
export default {
...
filters: {
formatDate (val) {
console.log(this) // 输出结果为undefined
return this.$moment(val).format('YYYY-MM-DD') // 报$moment()undefined
}
}
}
</script>
解决:
<template>
{{ formatDate('1558490001000') }}
</template>
<script>
export default {
...
computed: { // 使用计算属性
formatDate () {
return function (val) { // 对计算属性进行传参
return val ? this.$moment(val).format('YYYY-MM-DD HH:MM:SS') : ''
}
}
}
}
</script>
二、如果computed
满足不了你的需求,必须要使用filters
定义一个that,然后在beforeCreate设置that等于this,这样在filters中就可以获取到this了
<script>
let that
export default {
filters: {
getVal (val) {
console.log(that)
}
},
beforeCreate () {
that = this
},
}
</script>
使用filters传参,更方便
比如下面这个例子,template中是一个数组遍历,你需要通过props
里的一个属性来动态设置getVal
的值
<template>
<div>{{item.name | getVal(type)}}</div>
</template>
<script>
export default {
props: {
type: String
},
filters: {
getVal (val, type) {
if (type === 'xxx') {
return 'aaaa'
} else if (type === 'yyy') {
return 'bbb'
} else {
return 'ccc'
}
}
}
}
</script>
更多推荐
已为社区贡献25条内容
所有评论(0)