[英]Vue2: Can I pass an optional (global) filter into a reusable component?
I am quite new to Vue.我对 Vue 很陌生。 I am working on a table as component, which is supposed to be a lot of times.我正在处理一张桌子作为组件,这应该是很多次。 So far, so good, but now I want to use a filter, which can be optional passed into it.到目前为止,一切都很好,但现在我想使用一个过滤器,它可以是可选的传递给它。
That is how I "call" the table:这就是我“调用”表格的方式:
<table
:headers="headers"
:items="some.data"
></table>
data () {
return {
headers: [
{ title: 'date', value: ['date'], filter: 'truncate(0, 10, '...')' },
]
}
}
Here is my table component这是我的表格组件
<template>
<div>
<table class="table">
<thead>
<tr>
<!-- <th v-for="header in headers" :key="header.id" scope="col">{{ header.title }}</th> -->
<th v-for="header in headers" :key="header.id" scope="col">
{{ header.title }}
</th>
</tr>
</thead>
<tbody>
<tr v-for="item in items" :key="item.id" scope="col">
<td v-for="header in headers" :key="header.id" scope="row">
<!-- {{item}} -->
<span v-for="val in header.value" :key="val.id">
{{item[val] | truncate(0, 10, '...') }}
</span>
<!-- {{header.filter}} -->
</td>
</tr>
</tbody>
</table>
</div>
</template>
<script >
export default {
name: 'Table',
props: {
headers: Array,
items: Array
}
}
</script>
My global filter:我的全局过滤器:
Vue.filter('truncate', function (text, start, truncLength, clamp = '') {
return text.slice(start, truncLength) + clamp
// return text.slice(0, stop) + (stop < text.length ? clamp || ' ...' : '')
})
I was hopping, to add by that an optional filter (via v-if I would chech for it).我正在跳跃,添加一个可选的过滤器(通过 v-如果我愿意的话)。 So far I can render the filter as string... but not execute it.到目前为止,我可以将过滤器呈现为字符串......但不能执行它。
Even if I put the filter in the span, it does not work (it says then, "text.slice is not a function" in the console.即使我将过滤器放在跨度中,它也不起作用(然后在控制台中显示“text.slice 不是函数”。
I was not successful with googling it, because with filters/filter it is mostly about how to use.filter(...) on data as JS method, but not as Vue filter.我在谷歌上搜索它没有成功,因为过滤器/过滤器主要是关于如何在数据上使用 .filter(...) 作为 JS 方法,而不是作为 Vue 过滤器。
Any advise?有什么建议吗?
A filter is a function that runs inside JSX template in html.过滤器是在 html 中的 JSX 模板内运行的 function。 Example of how to create custom Vue.js filter如何创建自定义 Vue.js 过滤器的示例
Vue.filter('ssn', function (ssn) { // ssn filter
return ssn.replace(/(\d{3})(\d{2})(\d{4})/, '$1-$2-$3');
});
Using it使用它
{{stringToTrans | ssn}}
To use a filter outside this you can use a computed property or standard function like so要在此之外使用过滤器,您可以像这样使用计算属性或标准 function
convertedDateString() { // computed
return this.$moment(this.dateString).format('MM/DD/YYYY')
}
convertedDateString(dateString) { // method
return this.$moment(dateString).format('MM/DD/YYYY')
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.