3.vue计算属性和过滤器

1.计算属性

Vue中的computed属性称为计算属性.它与methods不同,computed是响应式的,调用时要向属性那样访问;同时computed是带缓存的,并不是每次调用时都会执行.

  • 练习1
<body>
        <div id="app">
            <button type="button" @click="git1">点击methods</button>
            <button type="button" @click="git2()">点击computed</button>
        </div>
        <script type="text/javascript">
            var app = new Vue({
                el: '#app',
                data: {
                    name1:'这是vue.js,的methods计算属性练习',
                    name2:'这是vue.js,的computed计算属性练习'
                },
                methods:{
                    git1:function(){
                        alert(this.name1)
                        console.log(this.name1)
                    }
                },
                computed:{
                    git2:function(){
                        alert(this.name2)
                        console.log(this.name2)
                    }
                }
            })
        </script>
    </body>

通过上列代码可知computed的执行方式,如果git2()不加括号,那么执行该代码是,git2()会预执行,然后就没办法调用了

  • 练习2
<body>
        <div id="app">
            <div class="container">
                <div class="item" v-for="goods in goodsList">
                    <div class="item-id">
                        {{goods.id}}
                    </div>
                    <div class="item-ava">
                        <a v-bind:href="goods.url"><img :src="goods.ava" width="30px"></a>
                    </div>
                    <div class="item-name">
                        {{goods.name}}
                    </div>
                    <div class="item-price">
                        {{goods.price}}
                    </div>
                    <div class="item-count">
                        <button type="button" @click="goods.count -= 1" :disabled="goods.count ===0||show">-</button>
                        <input type="text" v-model="goods.count" class="goods-count" />
                        <button type="button" @click="goods.count += 1" :disabled="show">+</button>
                    </div>
                </div>
                <hr>
                <div class="other">
                    <h3 class="pr">总价:{{totalPrice}}¥</h3>
                <button type="button" @click="handleClick" :disabled="show" class="but">结算</button>
                </div>
                <p v-if="show">共购买商品{{settlement}},共需支付:¥{{totalPrice}}</p>
            </div>
        </div>
        <script type="text/javascript">
            var app = new Vue({
                el: '#app',
                data: {
                    goodsList: [{
                        id: 1,
                        ava:'https://img.alicdn.com/imgextra/i3/13022581/O1CN01rnYEL91Uw8k0wAjU9_!!0-saturn_solar.jpg_240x240xz.jpg_.webp',
                        url:'https://detail.tmall.com/item.htm?id=580731960102&ali_refid=a3_430676_1006:1102515942:N:iphone%208:347c644f4a493b4d035f9f02db5f7ede&ali_trackid=1_347c644f4a493b4d035f9f02db5f7ede&spm=a231o.7712113/d.1004.1',
                        name: 'iphone 8',
                        price: 6000,
                        count: 1
                    }, {
                        id: 2,
                        ava:'https://img.alicdn.com/imgextra/i3/13022581/O1CN01rnYEL91Uw8k0wAjU9_!!0-saturn_solar.jpg_240x240xz.jpg_.webp',
                        url:'https://detail.tmall.com/item.htm?id=583972739234&ali_refid=a3_430676_1006:1102515942:N:apple%20x:9b5c2bb520cac851535eaf392aa45888&ali_trackid=1_9b5c2bb520cac851535eaf392aa45888&spm=a231o.7712113/d.1004.1',
                        name: 'iphone x',
                        price: 7000,
                        count: 1
                    }, {
                        id: 3,
                        ava:'https://img.alicdn.com/imgextra/i2/124432566/O1CN013XtsEY1UpGntTaVCu_!!0-saturn_solar.jpg_240x240xz.jpg_.webp',
                        url:'https://detail.tmall.com/item.htm?id=586330226433&ali_refid=a3_430676_1006:1150882196:N:iphone+x+max:22c28f58e18f669e791312d96439c840&ali_trackid=1_22c28f58e18f669e791312d96439c840&spm=a231o.7712113%2Fd.1004.128',
                        name: 'iphone xs Max',
                        price: 8000,
                        count: 1
                    }],
                    show:false
                },
                methods: {
                    handleClick:function(){
                        this.show = ! this.show;
                        
                    }
                },
                computed: {
                    totalPrice: function() {
                        var totalPrice = 0;
                        for (var i = 0, len = this.goodsList.length; i < len; i++) {
                            totalPrice += this.goodsList[i].price * this.goodsList[i].count;
                        }
                        return totalPrice;
                    },
                    settlement: function() {
                        this.show = true;
                        var totalCount = 0;
                        var len = this.goodsList.length;
                        for (var i = 0; i < len; i++) {
                            totalCount += this.goodsList[i].count;
                        }
                        return totalCount;
                    }
                }
            })
        </script>
    </body>

效果图

由于产品个数是双向绑定,所以可以添加或减少,而computed中引用的响应式属性发生变化后,总价和产品个数才会发生变化,其中:disabled如果一个元素不能被激活或获取焦点,则该元素处于被禁用状态。

  • 过滤器
    vue是需要自定义过滤器的
    <body>
        <div id="app">
            <div class="container">
                <input type="text" v-model="searchString" placeholder="请输入"/>
                <button type="button" @click="tf"">搜索</button>
                
                    <div class="item" v-for="article in filteredArticles" >
                    <div class="item-title">
                        <a :href="article.url" target="_blank">
                            {{article.title}}
                        </a>
                        <a :href="article.url" target="_blank">
                            <p>
                                {{article.infor}}
                            </p>
                        </a>
                    </div>
                    <div class="item-thumbnail">
                        <img :src="article.image">
                    </div>
                </div>
            </div>
        </div>
        <script type="text/javascript">
            var app = new Vue({
                el: '#app',
                data: {
                    searchString: "",
                    show:true,
                    articles: [{
                            "title": "堪称神器的3款在线工具,你一定用得上!",
                            "url": "https://www.jianshu.com/p/e83e7999346b",
                            "infor": "一款在线免费GIF编辑神器,提供在线GIF压缩、视频转GIF、GIF合成、GIF裁剪四个功能,用户无需安装任何插件就可以轻松的进行视频格式转换...",
                            "image": "https://upload-images.jianshu.io/upload_images/11438996-56b25f32c9307b4b?imageMogr2/auto-orient/strip%7CimageView2/2/w/640/format/webp"
                        },
                        {
                            "title": "经典面试题:从 URL 输入到页面展现到底发生什么?",
                            "url": "https://www.jianshu.com/p/45ba3e0d0c7e",
                            "infor": "打开浏览器从输入网址到网页呈现在大家面前,背后到底发生了什么?经历怎么样的一个过程?先给大家来张总体流程图,具体步骤请看下文分解!",
                            "image": "https://upload-images.jianshu.io/upload_images/3973862-d90954249a6f6ccd.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1000/format/webp"
                        },
                        {
                            "title": "如何免翻墙使用谷歌搜索和Chrome应用商店",
                            "url": "https://www.jianshu.com/p/484f8e6c88f6",
                            "infor": "可能大家都听过或正在使用谷歌浏览器,但是由于某种原因只能在谷歌浏览器使用百度搜索引擎,至于什么谷歌搜索引擎、谷歌商城、Gmail邮箱统...",
                            "image": "https://upload-images.jianshu.io/upload_images/858154-015a4b083685a3d1.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/800/format/webp"
                        },
                        {
                            "title": "四款前所未有好用的黑科技APP,绝对的良心实用,赶紧告诉家人",
                            "url": "https://www.jianshu.com/p/2aec84d269fe",
                            "infor": "手机微信、支付宝、淘宝等应用都是我们经常会使用到的APP,除此之外,我们就来就给...",
                            "image": "https://upload-images.jianshu.io/upload_images/16042993-168b2cb17fd7ec0c?imageMogr2/auto-orient/strip%7CimageView2/2/w/640/format/webp"
                        },
                        {
                            "title": "坚持学英语的方法有哪些",
                            "url": "https://www.jianshu.com/p/0a6a61b0933c",
                            "infor": "学习英语没有什么捷径,至少我认为,我一直以来都是自学英语,从没有听过课堂上老师是怎么讲英语的,都是通过听广播和看视频学会的。我想说...",
                            "image": "https://upload-images.jianshu.io/upload_images/3525704-c7293758fc59e56b.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/960/format/webp"
                        }
                    ]
                },
                computed: {
                    // 计算函数,匹配搜索
                    filteredArticles: function() {
                        var articles_array = this.articles,
                            searchString = this.searchString;
                        //搜索关键词为空,则返回原始数据集
                        if (!searchString) {
                            return articles_array;
                        }
                        //搜索关键词去除无用空格,转换为小写
                        searchString = searchString.trim().toLowerCase();
                        //过滤数组中每个元素
                        articles_array = articles_array.filter(function(item) {
                            if (item.title.toLowerCase().indexOf(searchString) !== -1) {
                                return item;
                            }
                        })
                        // 返回转化后的数组
                        return articles_array;
                    }
                }
            })
        </script>
    </body>

如上,在computed中filter()会过滤掉除了item以外的所有元素,最后返回的数组就只剩下了含item元素的数组

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 228,983评论 6 537
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 98,772评论 3 422
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 176,947评论 0 381
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 63,201评论 1 315
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 71,960评论 6 410
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 55,350评论 1 324
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 43,406评论 3 444
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 42,549评论 0 289
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 49,104评论 1 335
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 40,914评论 3 356
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 43,089评论 1 371
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 38,647评论 5 362
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 44,340评论 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 34,753评论 0 28
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 36,007评论 1 289
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 51,834评论 3 395
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 48,106评论 2 375

推荐阅读更多精彩内容