uni-app中过滤器的使用

uni-app中过滤器的使用

1.问题

请求了一个新闻接口,返回的发布时间数据如下:
在这里插入图片描述
渲染到页面之后:
在这里插入图片描述
并不是我想要的数据,我想到了vue中的过滤器,因为uni-app的绝大部分语法跟vue是一样的,所以想用vue的过滤器filters试试

2. 解决问题

在所使用的页面内添加过滤器,由于返回的数据是一个对象,所以先转成字符串,考虑到年月日有不满两位数的时候,使用padStart(2,0)进行补全

onLoad(){},
filters:{
			formatData(data){
				const nDate=new Date(data);
				const year = nDate.getFullYear().toString().padStart(2,0);
				const month = nDate.getMonth().toString().padStart(2,0);
				const day = nDate.getDay().toString().padStart(2,0);
				return year +'-'+ month +'-'+ day
			}
		},
methods:{}

页面使用过滤器,用管道符连接

<template>
	<view class="news_detail">
		<text class="title">{{detail.title}}</text>
		<view class="info">
			<text>发表时间:{{detail.add_time | formatDate}}</text>
			<text>浏览次数:{{detail.click}}</text>
		</view>
		<!-- <view class="content" v-html="detail.content"></view> -->
		<view class="content">
			<rich-text :nodes="detail.content"></rich-text>
		</view>
	</view>
</template>

然后测试页面显示
在这里插入图片描述
显示合适了

3. 升华一下

在开发时我发现还有页面要渲染的时间数据也这个格式的,所以果断将过滤器filters改为全局过滤器
在这里插入图片描述
将filters改为全局过滤器在main.js内添加
main.js

import Vue from 'vue'
import App from './App'
Vue.filter("formatDate",(data)=>{
	const nDate=new Date(data);
	const year = nDate.getFullYear().toString().padStart(2,0);
	const month = nDate.getMonth().toString().padStart(2,0);
	const day = nDate.getDay().toString().padStart(2,0);
	return year +'-'+ month +'-'+ day
})

Vue.config.productionTip = false

App.mpType = 'app'

const app = new Vue({
    ...App
})
app.$mount()

页面中不需要再添加过滤器了,直接在要使用的地方用管道符链接添加即可

<template>
	<view>
		<view
			class="news_item"
			v-for="(v,i) in data"
			:key="i"
			@click="navigator(v.id)"
		>
			<image :src="v.img_url"></image>
			<view class="right">
				<view class="tit">
					{{v.title}}
				</view>
				<view class="info">
					<text>发表时间:{{v.add_time | formatDate}}</text>
					<text>浏览次数:{{v.click}}</text>
				</view>
			</view>
		</view>
	</view>
</template>

  • 11
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值