Vue全局注冊過濾器


傳統注冊過濾器

1、先在 filters/index.js 文件中導出方法

/**
 *
 * @param {*} date
 * @returns
 */
export function dateTimeFormat(date) {
  const json_date = new Date(date).toJSON()
  console.log(json_date)
  return new Date(+new Date(json_date) + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '')
}

 

2、在 main.js 中導入方法並注冊

import { dateTimeFormatData } from '@/filters' // 引入工具類
Vue.filter("dateTimeFormatData ", dateTimeFormatData )

 

3、在組件中使用過濾器

<el-table-column
  prop="timeOfEntry"
  label="入職時間"
  width="120"
>
  <template slot-scope="row">
    {{ row.row.timeOfEntry | dateTimeFormat }}
  </template>
</el-table-column>

 

缺點:main.js 中需要一個個導入方法並注冊

使用全局方式導入所有的過濾器

1、在 filters/index.js 中導出方法

/**
 *
 * @param {*} date
 * @returns
 */
export function dateTimeFormat(date) {
  console.log(date)
  const json_date = new Date(date).toJSON()
  console.log(json_date)
  return new Date(+new Date(json_date) + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '')
}

/**
 *
 * @param {*} date
 * @returns
 */
export function dateTimeFormatData(date) {
  const d = new Date(date)
  return d.getFullYear() + '-' + (d.getMonth() + 1 < 10 ? '0' + (d.getMonth() + 1) : d.getMonth() + 1) + '-' + (d.getDate() < 10 ? '0' + d.getDate() : d.getDate())
}

 

2、在 main.js 中統一注冊過濾器

import * as filters from '@/filters' // 引入工具類

Object.keys(filters).forEach(key => {
  // 注冊過濾器
  Vue.filter(key, filters[key])
})

 

3、在組件中使用過濾器

<el-table-column
  prop="timeOfEntry"
  label="入職時間"
  width="120"
>
  <template slot-scope="row">
    {{ row.row.timeOfEntry | dateTimeFormat }}
  </template>
</el-table-column>

<el-table-column
  prop="timeOfEntry"
  label="入職時間"
  width="120"
>
  <template slot-scope="row">
    {{ row.row.timeOfEntry | dateTimeFormat}}
  </template>
</el-table-column>

 

優點:一次性將 filters/index.js 中的方法導入,並使用循環注冊過濾器


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM