有时我们写过滤器的时候会用到this,但是在过滤器的方法中取不到 this ,那就在 data 中定义一个属性 that 将 this 存到 that 中,然后通过过滤器方法传参的办法将 that 传到过滤器中
【问题】过滤器中取不到this
<el-table
v-loading="tableLoading"
:data="tableData"
size="small"
row-key="dwdm"
:tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
:default-expand-all="true"
>
<el-table-column type="index" label="序号" align="center" :show-overflow-tooltip="true">
</el-table-column>
<el-table-column prop="dwdm" label="管理部门" :show-overflow-tooltip="true">
<template slot-scope="{ row }">
<span>{{ row.dwdm | filterDwdm }}</span>
</template>
</el-table-column>
</el-table>
export default {
filters: {
filterDwdm(val) {
console.log('val----', val)
console.log('this----', this) // undefined
return this.glbmOptions.filter((item) => item.value === val)[0].label
}
}
}
this 为 undefined 并且会报错
问题解决
在 data 中定义一个属性 that 将 this 存到 that 中,然后通过过滤器方法传参的办法将 that 传到过滤器中
<el-table
v-loading="tableLoading"
:data="tableData"
size="small"
row-key="dwdm"
:tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
:default-expand-all="true"
>
<el-table-column type="index" label="序号" align="center" :show-overflow-tooltip="true">
</el-table-column>
<el-table-column prop="dwdm" label="管理部门" :show-overflow-tooltip="true">
<template slot-scope="{ row }">
<!-- 将 that 传到过滤器中 -->
<span>{{ row.dwdm | filterDwdm(that) }}</span>
</template>
</el-table-column>
</el-table>
export default {
data() {
return {
that: this,
}
},
filters: {
filterDwdm(val, that) {
console.log('val----', val)
console.log('that----', that) // 取到的内容时this的值
return that.glbmOptions.filter((item) => item.value === val)[0].label
}
}
}