二、全局过滤器转换时间戳。

167 阅读1分钟

theme: smartblue

Vue实现时间转换全局过滤器

在main.js中注册全局过滤器


 Vue.filter('forMat', (data) => {
 
  const t = new Date(data)
  
  const yy = t.getFullYear()
  
  const mm = (t.getMonth() + 1).toString().padStart(2, 0)
  
  const dd = t.getDate()
  return `${yy}-${mm}-${dd}`
## })

使用方法

格式: 在模板中用管道符|分割开{{data里的变量名|过滤器函数名()}}

//4. 渲染数据,设置过滤器
 {{ scoped.row.timeOfEntry | forMat("YYYY-MM-DD") }}

局部过滤器的使用

<template>
  <div>
    <!-- 5. 放过滤器 -->
    {{ times | conversion | againChange }}
  </div>
</template>

<script>
export default {
  // 2. 定义过滤器
  filters: {
    // 3.定义一个处理函数,参数value为要处理数据
    conversion: function(value) {
      // 调用Date的方法,处理时间戳
      return new Date(value).toLocaleString()
    },
    // 4.再定义一个过滤器,给数据前加上"时间为:"这几个字
    againChange: function(value) {
      return '时间为:' + value
    }
  },
  data() {
    return {
      // 1.模拟一个时间戳数据
      times: 1616959086000
    }
  }

}
</script>

每天进步一点,前端入门到入土