Vue filter filters

scenes to be used

Used for some common text formatting. Maybe the data format returned by the backend is not what you want to display in the end, and you can process it into the format you want to display through the filter. Indicated by the "pipe" symbol.

How to use

1. Double curly braces interpolation

{
    
    {
    
    message | myFilter}}

2. v-bind expression

<el-tag :type="message | myFilter"></el-tag>

3. In the life cycle of vue, such as used in the methods method

this.$options.filters['这里是过滤器的名字']('过滤器的参数')

4. Can also accept functions as parameters

this.$options.filters['这里是过滤器的名字']('参数一', this.fun('zhangyue'))

5. Filters can be connected in series, and the result of filterA will be passed into the parameter of filterB

{
    
    {
    
    message | filterA | filterB}}

example

When v-for loop renders an array object
example one
const arr = [
{
    
    
	id: 1,
	name: '张张'
},
{
    
    
	id: 2,
	name: '悦悦'
}
]
<ul>
	<li v-for="item in arr" :key="item.id">{
    
    {
    
    item | myFilterA | myFilterB}}</li>
</ul>
export default {
    
    
	filters: {
    
    
		myFilterA(message) {
    
    
			return '我是' + message
		},
		myFilterB(message) {
    
    
			return message + '串联咯'
		}
	}
}

final output

我是张张串联咯
我是悦悦串联咯
example two
<el-table-column
  label="status"
  width="100"
>
  <template slot-scope="scope">
    <el-tag :type="scope.row.status | statusFilter">{
    
    {
    
    
      scope.row.status
    }}</el-tag>
  </template>
</el-table-column>
export default {
    
    
  filters: {
    
    
    statusFilter(status) {
    
    
      const statusMap = {
    
    
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  }
}

Replenish

{
    
    {
    
    message | filterA('arg1', 'arg2')}}

filterA is defined as a filter function that receives 3 parameters. message as the first parameter, arg1 as the second parameter, and arg2 as the third parameter.
What we have said above is to define local filters. Let's take a look at the definition of global filters mentioned on the official website.
Define the filter globally before creating the vue instance

Vue.filter('capitalize', function (value) {
    
    
  if (!value) return ''
  value = value.toString()
  return value.charAt(0).toUpperCase() + value.slice(1)
})

new Vue({
    
    
  // ...
})

When the global filter and the local filter have the same name, the local filter will be adopted.

Guess you like

Origin blog.csdn.net/zhangxiaodui/article/details/123127341