vue filter的用法

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

vue filter的用法

大灰狼的小绵羊哥哥   2022-05-28 我要评论

filter的用法小结

使用计算属性app.js

var app5 = new Vue({
    el: '#app5',
    data: {
        shoppingList: [
            "Milk", "Donuts", "Cookies", "Chocolate", "Peanut Butter", "Pepto Bismol", "Pepto Bismol (Chocolate flavor)", "Pepto Bismol (Cookie flavor)"
        ],
        key: ""
    },
    computed: {
        filterShoppingList: function () {
            // `this` points to the vm instance
            var key = this.key;
            var shoppingList = this.shoppingList;
            return shoppingList.filter(function (item) {
                return item.toLowerCase().indexOf(key.toLowerCase()) != -1
            });;
        }
    }
})

app.html

<div id="app5">
        <h2>Vue-for</h2>
        <ul>
            <li v-for="item in shoppingList">
                {{ item }}
            </li>
        </ul>
        <h2>Vue-for filter实现</h2>
        <ul>
            Filter Key<input type="text" v-model="key">   
            <li v-for="item in filterShoppingList">
                {{ item }}
            </li>
        </ul>        
    </div>    

最终效果实现了根据关键字来过滤列表的功能。 

filter的基本用法

filter是和data  computed   methods watch一样,都是new Vue()的参数。

用于对简单数据的处理,和computed有冲突,所以从vue2.0后就对filter做了删减,我觉得没有filter完全能够用其他方法比如computed来实现

用在{{ 变量1 | 变量2 }} 或者 v-bind:xx=“  变量1 | 变量2([参数) ”  两种;其中变量1是data的k,变量2是filter的k,

filter:{ 变量2:function(变量1,参数){xxxx}}

<div id="app">
        <div> {{val | upcaseVal(true)}}</div>
        <div v-bind:title="val | upcaseVal">{{val}}</div>
        <div>{{val | removeSpace}}</div>
    </div>
    <script>
        var vm = new Vue({
            el: '#app',
            data: {
                val: 'hello world'
            },
            filters: {
                upcaseVal: function (val, firstUpper) {//filter里函数的参数需要特别注意 第一个是指|前的值,第二个是true
                    if (firstUpper) {
                        return val.split(' ').map(function (e) {
                            return e[0].toUpperCase() + e.slice(1)
                        }).join(' ')
                    }
                    return val.toUpperCase();
                },
                removeSpace:function(val){
                    return val.toUpperCase()
                }
            }
        })

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们