前言
- 本篇来学习vue(仅适用vue2)中过滤器的基本用法
过滤器
- 过滤器(Filters)是vue为开发者提供的功能,常用于文本的格式化。可以用在两个地方:插值表达式和v-bind属性绑定。
私有过滤器
插值表达式中使用
<p>{{message | capital }}p>
使用示例
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>过滤器基本使用title>
head>
<body>
<div id="app">
<p>{{message | capital }}p>
div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js">script>
<script>
const app = new Vue({
el: '#app',
data: {
message: 'hello 小白!'
},
filters: {
capital(val) {
console.log(val.charAt(0))
const first = val.charAt(0).toUpperCase()
const other = val.slice(1)
return first + other
}
}
})
script>
body>
html>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
<input type="text" v-bind:placeholder="message|capital">
使用示例
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>过滤器基本使用title>
head>
<body>
<div id="app">
<input type="text" v-bind:placeholder="message|capital">
div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js">script>
<script>
const app = new Vue({
el: '#app',
data: {
message: 'hello 小白!'
},
filters: {
capital(val) {
console.log(val.charAt(0))
const first = val.charAt(0).toUpperCase()
const other = val.slice(1)
return first + other
}
}
})
script>
body>
html>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
全局过滤器
- 使用Vue.filter()定义全局过滤器;接收两个参数 第一个全局过滤名称,第二个 全局过滤器的处理函数
使用示例
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>过滤器基本使用title>
head>
<body>
<div id="app">
<p>{{message | capital }}p>
div>
<div id="app2">
<input type="text" v-bind:placeholder="message|capital">
div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js">script>
<script>
Vue.filter('capital', function (val) {
console.log(val.charAt(0))
const first = val.charAt(0).toUpperCase()
const other = val.slice(1)
return first + other
})
const app = new Vue({
el: '#app',
data: {
message: 'hello 小白!'
}
})
const app2 = new Vue({
el: '#app2',
data: {
message: 'hello 大海!'
}
})
script>
body>
html>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47