uni-app中过滤器的使用

uni-app中过滤器的使用

1.问题

请求了一个新闻接口,返回的发布时间数据如下:
uni-app中过滤器的使用_第1张图片
渲染到页面之后:
uni-app中过滤器的使用_第2张图片
并不是我想要的数据,我想到了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">
			<rich-text :nodes="detail.content">rich-text>
		view>
	view>
template>

然后测试页面显示
uni-app中过滤器的使用_第3张图片
显示合适了

3. 升华一下

在开发时我发现还有页面要渲染的时间数据也这个格式的,所以果断将过滤器filters改为全局过滤器
uni-app中过滤器的使用_第4张图片
将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>

你可能感兴趣的:(uni-app)