vue filter的使用

vue filter的使用

过滤器是什么?
 过滤器就是将后台返回的数据换一种形式输出,不改变原来的数据。

应用的场景:后台返回状态码  例如(性别,支付状态,时间 ),商品价格

过滤器: 有全局过滤器 和 局部过滤器

全局过滤器:

	全局过滤器必须写在vue实例创建之前。
Vue.filter('testfilter', function (value,text) {
   // 返回处理后的值
   return value+text
  })

局部过滤器

 局部过滤器必须在组件实例对象里挂载。
filters: {
    changemsg:(val,text)=>{
        return val + text
    }
},

全局的和局部的写法要注意:全局注册时filter,没有S,而组件过滤器是有S的,虽然你不写S的时候不报错,但是过滤器是没有效果的

过滤器的使用:

只能使用在{{}}和:v-bind中,定义时第一个参数固定为预处理的数,后面的数为调用时传入的参数,调用时参数第一个对应定义时第二个参数,以此类推;

	1、在{{}}括号里插值  :
		
		{{ 'sere' | Goods }}
	
	2、在v-bind表达式中使用:
			
			<div v-bind:data="'sere' | Goods "></div>

案例演示

一、在vue中创建一个组件home.vue;

<template>
  <div class="home">
    <header class="home_header">头部</header>
    <main class="home_box">
      <ul>
        <li v-for="(item, index) in list" :key="index">
          <p>商品名称:{{ item.name }}</p>
          <p>商品价格:{{ item.price | currency("¥") }}</p>
          <p>商品状态:{{ item.isPay | pay() }}</p>
        </li>
      </ul>
    </main>
  </div>
</template>

<script>
export default {
  name: "Home",
  data() {
    return {
      list: [
        { id: 1001, name: "iphone", price: 2332200, isPay: 1 },
        { id: 1002, name: "华为", price: 2323200, isPay: 0 },
        { id: 1003, name: "oppo", price: 234333300, isPay: 1 },
        { id: 1004, name: "诺基亚", price: 23054540, isPay: 0 },
        { id: 1005, name: "8848钛晶手机", price: 23656500, isPay: 1 }
      ]
    };
  },
  components: {}
};
</script>

<style lang="scss" scoped>
.home_header {
  width: 100%;
  height: 50px;
  background-color: salmon;
  text-align: center;
  line-height: 50px;
}
.home_box {
  ul li {
    width: 40%;
    height: 60px;
    border: 1px solid #f00;
    margin-top: 10px;
  }
}
</style>

二、在src目录下创建一个文件 例如: filters–> index.js

// 全局过滤器  货币格式
export function currency(v, type) {
  //   console.log("返回值", type + v);
  
   /*在这里使用的是千位符分割方*/
  let result = v && v.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,");
  return type + result;
}

// 支付状态的处理
export function pay(v) {
  let payText = "";
  switch (v) {
    case 0:
      payText = "已支付";
      break;
    case 1:
      payText = "未支付";
      break;
    default:
      payText = "未知状态";
      break;
  }
  return payText;
}

三、在main.js里面引入注册;

import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";

//引入过滤器的函数
import * as filters from "./filters/index";
console.log(filters);

Object.keys(filters).forEach(key => {
  Vue.filter(key, filters[key]);
});
Vue.config.productionTip = false;

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount("#app");

猜你喜欢

转载自blog.csdn.net/qq_43036190/article/details/106407516