过滤器的使用
关于过滤器的使用其实很简单
<template>
<view class="content">
<view>
<view>{{num|double}}</view> //6
<view>{{num|double(3)}}</view> //9
</view>
</view>
</template>
<script>
export default {
data() {
return {
num:3
}
},
filters: {
double(value,tag=2){
return value*tag;
}
}
}
</script>
封装多个全局过滤器
1.在src下创建filters文件夹,并新建index.js文件
- index.js里面的代码
const new_price = (price) => {
if(price > 1){
price = Math.floor(price)
}else{
price = price
}
return price
}
const date_filter = (v,new_date) => {
let date = new Date(v * 1000); //时间戳为10位需*1000,时间戳为13位的话不需乘1000
var Y = date.getFullYear() + '-';
var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
var D = date.getDate() + ' ';
var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes());
var s = date.getSeconds();
if(new_date == "M-D h-m"){
return M + D + h + m
}
if(!new_date){
return Y + M + D + h + m + s
}
}
export{
new_price,
date_filter
}
3、main.js里面添加
import * as filters from './filters'
Object.keys(filters).forEach(key =>{
Vue.filter(key,filters[key])
})
4、在vue文件中就可以直接使用了
<span>{{price | new_price}}</span>
mixin混入
Vue.mixin给我们提供了一种混入Vue实例的方法,创建了混入对象之后,我们自定义的方法或者变量可以很轻松的挂载在Vue实例上,给我们的偷懒带来方便;不只是methods,还有生命周期
//uniapp的代码
//封装的mixin文件
export const common = {
onLoad(){
//优先顺序:mixin_onload > page_onload > mixin_onshow > page_onshow
this.check_login()
},
methods: {
check_login() {
console.log('检查登录')
},
log() {
console.log('aaaaaaaaa')
}
}
}
//自动执行了check_login(),log()函数
<script>
import {common} from "../../common/mixin.js"
export default {
data() {
return {
};
},
mixins:[common],
//先执行了mixin中的onLoad函数的check_login()
onShow(){
this.a()
},
methods: {
this.a(){
this.log() //mixin中的函数
}
}
</script>
网友评论