vue-java-tutorials/vue2-tutorials/import-script/13-过滤器.md

144 lines
3.9 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Vue2 过滤器(Filter)使用指南
## 一、基本概念
过滤器(Filters)是Vue2中用于文本格式化处理的特殊函数可以在模板中使用管道符(`|`)对数据进行转换处理。
## 二、代码示例解析
```html
<div id="app">
<!-- 使用局部过滤器 -->
<h3>现在是:{{time | timeFormater}}</h3>
<!-- 传参的过滤器 -->
<h3>现在是:{{time | timeFormater("YYYY年MM月DD日 HH:mm:ss")}}</h3>
<!-- 过滤器链式调用 -->
<h3>现在是:{{time | timeFormater("YYYY年MM月DD日 HH:mm:ss") | timeFormaterSlice}}</h3>
<!-- 使用全局过滤器 -->
<h3 :peiqi="message | globeTimeFormaterSlice">
使用全局过滤器:{{message | globeTimeFormaterSlice}}
</h3>
</div>
<script>
// 全局过滤器定义
Vue.filter("globeTimeFormaterSlice", function(val) {
return val.slice(0, 4);
});
const vm = new Vue({
el: "#app",
data: {
time: new Date(),
message: "全局的过滤器使用在标签上..."
},
filters: {
// 局部过滤器定义
timeFormater(val, str = "YYYY-MM-DD HH:mm:ss") {
return dayjs(val).format(str);
},
timeFormaterSlice(val) {
return val.slice(0, 4);
}
}
});
</script>
```
## 三、核心特性
### 1. 过滤器类型
| 类型 | 定义位置 | 作用域 | 示例 |
| ---------- | ---------------------- | -------- | --------------------------- |
| 局部过滤器 | Vue实例的`filters`选项 | 当前组件 | `{{ data | localFilter }}` |
| 全局过滤器 | `Vue.filter()` | 所有组件 | `{{ data | globalFilter }}` |
### 2. 使用方式
| 方式 | 语法 | 说明 |
| -------- | --------------------------------- | ------------------ |
| 基本使用 | `{{ data | filter }}` | 单个过滤器 |
| 传参使用 | `{{ data | filter(arg1, arg2) }}` | 可传递额外参数 |
| 链式调用 | `{{ data | filter1 | filter2 }}` | 多个过滤器依次处理 |
## 四、最佳实践
### 1. 命名规范
- 使用动词+名词形式(如`formatDate`、`truncateText`
- 全局过滤器加前缀(如`globe_`)避免命名冲突
### 2. 适用场景
- 文本格式化(日期、货币等)
- 数据简单转换(截取、大小写转换等)
- 显示内容的修饰(添加前缀/后缀)
### 3. 注意事项
- **不能**在`v-model`中使用
- **避免**复杂业务逻辑,复杂处理应使用计算属性
- **推荐**纯函数实现,不要修改原始数据
## 五、高级用法
### 1. 动态过滤器名
```javascript
filters: {
dynamicFilter(val, filterName) {
return this[filterName](val);
}
}
```
### 2. 过滤器工厂函数
```javascript
function createPrefixFilter(prefix) {
return function(val) {
return prefix + val;
}
}
Vue.filter('withPrefix', createPrefixFilter('Info: '));
```
### 3. 结合计算属性使用
```javascript
computed: {
formattedTime() {
return this.$options.filters.timeFormater(this.time);
}
}
```
## 六、与Vue3的区别
| 特性 | Vue2 | Vue3 |
| ---------- | ------ | ----------------- |
| 过滤器支持 | ✅ 支持 | ❌ 移除 |
| 替代方案 | - | 使用方法/计算属性 |
## 七、常见问题
1. **为什么过滤器不生效?**
- 检查过滤器名称拼写
- 确认是否在正确的作用域定义
- 确保返回值不是undefined
2. **如何调试过滤器?**
```javascript
filters: {
debugFilter(val) {
console.log('Filter input:', val);
return val;
}
}
```
3. **过滤器能接收多个参数吗?**
```html
<!-- 可以,第一个参数永远是管道符前的值 -->
{{ data | filter(arg1, arg2) }}
```