vue-day21-过滤器学习

发布时间 2023-07-16 13:26:18作者: 雪落无痕1
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>过滤器</title>
<script type="text/javascript" src="../js/vue.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/dayjs/1.11.7/dayjs.min.js"></script>
</head>
<body>
<div id="root">
<!--
过滤器
定义:对要显示的数据惊醒特定格式后再显示(适用于一些简单的逻辑处理)
语法:
1.注册过滤器 Vue.filter(name, callback) 或者new Vue(filters: {})
2.使用过滤器 {{xxx | 过滤器名}} 或 v-bind:属性=“xxx | 过滤器名”
备注
1.过滤器可以接收额外参数,多个过滤器也可以串联
2.并没有改变原本的数据,是产生新的对象数据

-->
<h2>显示格式化的时间</h2>

<h3>计算属性实现现在的时间是{{fmttime}}</h3>
<h3>methods方法实现现在的时间是{{getFmtTime()}}</h3>
<h3>过滤器实现现在的时间是{{time | timeFormater}}</h3>
<h3>
过滤器实现(传参数)现在的时间是{{time | timeFormater("YYYY-MM-DD")}}
</h3>

<h3>多个过滤器串联实现现在的时间是{{time | timeFormater | myslice}}</h3>
<h3 ;x="msg | myslice">尚硅谷</h3>
</div>
<!-- https://www.bootcdn.cn/ 里面有很多库-->
<script type="text/javascript">
Vue.filter("myslice", function (value) {
return value.slice(0, 4);
});
const vm = new Vue({
el: "#root", //el用于指定当前vue实例为那个容器服务,但通常为css选择器字符串
data: {
time: 1689482154306,
msg: "你好呀,郑西行",
},

// 计算属性实现
computed: {
fmttime() {
return dayjs(this.time).format("YYYY-MM-DD HH:mm:ss");
},
},
methods: {
getFmtTime() {
return dayjs(this.time).format("YYYY-MM-DD HH:mm:ss");
console.log(JSON.stringify(this.userinfo));
},
},

//局部过滤器
filters: {
timeFormater(value, str = "YYYY-MM-DD HH:mm:ss") {
console.log("9999==" + value);
return dayjs(value).format("YYYY-MM-DD HH:mm:ss");
},

myslice(value) {
return value.slice(0, 4);
},
},
});
</script>
</body>
</html>