vue中filter(过滤器)的使用

时间:2025-01-19 08:21:46

1. 全局注册

(过滤器的名称, 函数)

html:

<div >
      <ul>
        <li v-for="item in teachers" :key="">
          {{  }} 生于:{{  | dateFormat("YY-MM-DD") }}
        </li>
      </ul>
 </div>
 <script src="./node_modules/vue/dist/"></script>
 <script src="./node_modules/moment/"></script>

函数接收的参数就是 | 前面的数据

在使用过滤器的时候 只需要在数据后面加上 |

数据 | 过滤器名称

 

数据 | 过滤器名称(参数)

过滤器函数中第一个参数,就是要过滤的数据

("dateFormat", function(value, pattern){
        // value就是用户给的时间对象
        return moment(value).format(pattern)

      })

2. 局部注册

const vm = new Vue({
        el: "#app",
        data: {
          teachers: [
            {
              id: 1,
              name: "aa",
              birthDay: new Date("1992-05-08")
            },
            {
              id: 2,
              name: "bb",
              birthDay: new Date("1992-06-08")
            },
            {
              id: 3,
              name: "cc",
              birthDay: new Date("1993-05-08")
            },

            {
              id: 4,
              name: "dd",
              birthDay: new Date("2002-05-08")
            }
          ]
        }
      });

 

其它使用:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
  </head>
  <body>
    <div >
      <ul>
        <li v-for="item in students" :key="">
          <span>{{}}</span>====<span>{{ | genderFilter}}</span>
        </li>
      </ul>
    </div>
    <script src="./node_modules/vue/dist/"></script>
    <script>

      ("genderFilter", function(value){
        switch(value){
          case 0: 
            return "female"
          case 1:
            return "male"
          case -1:
            return "unknow"
        }
      })
      
      const vm = new Vue({
        el: "#app",
        data: {
          students: [
            {id: 1, name: "aa", gender: 1},
            {id: 2, name: "bb", gender: 0},
            {id: 3, name: "cc", gender: 1},
            {id: 4, name: "dd", gender: -1},
            {id: 5, name: "ee", gender: 0}
          ]
        }
      });


     
    </script>
  </body>
</html>