Vue.js:計(jì)算屬性和過濾器

計(jì)算屬性(computed)钓觉,主要用于處理一些復(fù)雜邏輯。

基礎(chǔ)例子

<div id="app">
  <p>原始字符串: {{ message }}</p>
  <p>計(jì)算后反轉(zhuǎn)字符串: {{ reversedMessage }}</p>
</div>
 
<script>
var vm = new Vue({
  el: '#app',
  data: {
    message: 'Runoob!'
  },
  computed: {
    // 計(jì)算屬性的 getter
    reversedMessage: function () {
      // `this` 指向 vm 實(shí)例
      return this.message.split('').reverse().join('')
    }
  }
})
</script>

computed vs methods

我們可以使用 methods 來替代 computed讹堤,效果上兩個(gè)都是一樣的歇攻,但是 computed 是基于它的依賴緩存粗恢,只有相關(guān)依賴發(fā)生改變時(shí)才會(huì)重新取值。而使用 methods 片酝,在重新渲染的時(shí)候囚衔,函數(shù)總會(huì)重新調(diào)用執(zhí)行。使用 computed 性能會(huì)更好雕沿,但是如果你不希望緩存练湿,可以使用 methods 屬性藐守。

例1:購(gòu)物車價(jià)格計(jì)算

<!DOCTYPE html>
<html class="no-js">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>vue.js computed練習(xí)-計(jì)算購(gòu)物車總價(jià)</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <style type="text/css">
        .container {
            display: felx;
            width: 370px;
            margin: 0 auto;
            flex-direction: column;
        }
        .item {
            display: flex;
            border: 1px solid #000;
            border-radius: 10px;
            width: 350px;
            height: 50px;
            margin-bottom: 10px;
            /* 垂直方向居中 */
            align-items: center;
            /* 水平方向居中 */
            /* justify-content: center; */
            padding-left: 10px;
            padding-right: 10px;
        }
        .item-id {
            flex: 1 1 15%;
        }
        .item-cover {
            flex: 1 1 10%;
        }
        .item-name {
            flex: 1 1 30%;
        }
        .item-price {
            flex: 1 1 20%;
        }
        .item-count {
            flex: 1 1 25%;
        }
        .goods-count {
            width: 20px;
        }
        .totalPrice {
            display: flex;
            width: 370px;
            justify-content: space-between;
            align-items: center;
        }
        .btn-settle {
            width: 100px;
            height: 30px;
            background-color: #87CEEB;
            border-radius: 5px;
            border: none;
            outline: none;
            color: #FFF;
            font-size: 16px;
        }
    </style>
</head>
<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-cover">
                    <a v-bind:href="goods.url"  target="_blank"><img :src="goods.cover" width = "35"/></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 || settled">-</button>
                    <input type="text" class="goods-count" v-model="goods.count" />
                    <button type="button" @click="goods.count += 1" :disabled="settled">+</button>
                </div>
            </div>
            <div class="totalPrice">
                <h3>Total Price</h3>
                <p>¥{{totalPrice}}</p>
                <button type="button" class="btn-settle" @click="settle" :disabled="settled">結(jié)算</button>
            </div>
            
            <div class="price" v-if="settled">
                <p>您購(gòu)買了{(lán){totalCount}}件商品廊镜,需要支付總價(jià)為:{{totalPrice}}</p>
            </div>
        </div>
    </div>
    <script type="text/javascript">
        var app = new Vue({
            el: '#app',
            data: {
                goodsList: [
                    {
                        id : 1,
                        name : 'iPhone 8',
                        price : 3999,
                        url: "https://item.jd.com/5089267.html",
                        cover: "https://ss2.baidu.com/6ONYsjip0QIZ8tyhnq/it/u=3841252853,949538163&fm=58",
                        count : 1,
                    },
                    {
                        id : 2,
                        name : 'iPhone X',
                        price : 6349,
                        url: "https://item.jd.com/5089253.html",
                        cover: "https://ss2.baidu.com/6ONYsjip0QIZ8tyhnq/it/u=3159575759,329221210&fm=58",
                        count : 1,
                    },
                    {
                        id : 3,
                        name : 'iPhone Xs',
                        url: "https://item.jd.com/100000177748.html",
                        cover: "http://2c.zol-img.com.cn/product_small/13_120x90/816/cenfNF9Ndm2Y.jpg",
                        price : 7899,
                        count : 1,
                    },
                ],
                settled: false,
            },
            methods: {
                settle:function() {
                    this.settled = true;
                }
            },
            computed: {
                totalPrice:function() {
                    var totalPrice = 0;
                    for(var i = 0; i < this.goodsList.length; i ++) {
                        totalPrice += this.goodsList[i].price * this.goodsList[i].count;
                    }
                    return totalPrice;
                },
                totalCount:function() {
                    var totalCount = 0;
                    for(var i = 0; i < this.goodsList.length; i ++) {
                        totalCount += this.goodsList[i].count;
                    }
                    return totalCount;
                }
            },
        })
    </script>
</body>

</html>

例2:搜索頁(yè)面

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>Vue.js computed練習(xí)-搜索頁(yè)面的實(shí)現(xiàn)</title>
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
        <style type="text/css">
            * {
                margin: 0;
                padding: 0;
                box-sizing: border-box;
            }
            a {
                text-decoration: none;
                color: #333; 
            }
            .container {
                width: 95%;
                margin: 0 auto;
            }
            .input {
                display: flex;
                width: 100%;
                margin: 0 auto;
                flex-direction: row;
                margin-top: 10px;
                margin-bottom: 20px;
            }
            .input-box {
                flex: 1 1 70%;
                margin-right: 5%;
                border-radius: 5px;
                border: 1px solid #eee;
            }
            .search-btn {
                flex: 1 1 30%;
                height: 30px;
                background-color: #87CEEB;
                border-radius: 5px;
                border: none;
                outline: none;
                color: #FFF;
                font-size: 16px;
            }
            .item {
                display: flex;
                border: 1px solid #eee;
                border-radius: 8px;
                margin-bottom: 8px;
                height: 100%;
            }
            .item-text {
                flex: 1 1 65%;
                margin: 8px;
            }
            .item-title {
                font-size: 18px;
                font-weight: bold;
            }
            .item-content {
                color: #B4B4B4;
                font-size: 15px;
            }
            .item-thumbnail {
                flex: 1 1 35%;
                margin: 15px;
                display: table-cell;
                text-align: center;
                vertical-align: middle;
            }

            .item-thumbnail img {
                max-width: 100%;
                height: 100px;
            }
        </style>
    </head>
    <body>
        <div id="app">
            <div class="container">
                <div class="input">
                    <input type="text" v-model="searchString" placeholder="  請(qǐng)輸入" class="input-box" />
                    <button type="button" class="search-btn" @click="search">搜索</button>
                </div>
            
                <div v-if="flag">
                    <div class="item" v-for="article in filteredArticles">
                        <div class="item-text">
                            <p class="item-title"><a :href="article.url" target="_blank">{{article.title}}</a></p>
                            <p class="item-content">{{article.content}}</p>
                        </div>
                        <div class="item-thumbnail">
                            <img :src="article.image">
                        </div>
                    </div>
                </div>
                
                <div v-else>
                    <div class="item" v-for="article in articles">
                        <div class="item-text">
                            <p class="item-title"><a :href="article.url" target="_blank">{{article.title}}</a></p>
                            <p class="item-content">{{article.content}}</p>
                        </div>
                        <div class="item-thumbnail">
                            <img :src="article.image">
                        </div>
                    </div>
                </div>
                

            </div>
        </div>
        <script type="text/javascript">
            var app = new Vue({
                el: '#app',
                data: {
                    searchString: "",
                    // 數(shù)據(jù)模型
                    articles: [{
                            "title": "堪稱神器的3款在線工具,你一定用得上脾猛!",
                            "url": "http://www.reibang.com/p/e83e7999346b",
                            "image": "https://upload-images.jianshu.io/upload_images/11438996-56b25f32c9307b4b?imageMogr2/auto-orient/strip%7CimageView2/2/w/640/format/webp",
                            "content": "一款在線免費(fèi)GIF編輯神器,提供在線GIF壓縮贤姆、視頻轉(zhuǎn)GIF榆苞、GIF合成、GIF裁剪四個(gè)功能霞捡,用戶無需安裝任何插件就可以輕松的進(jìn)行視頻格式...",
                        },
                        {
                            "title": "經(jīng)典面試題:從 URL 輸入到頁(yè)面展現(xiàn)到底發(fā)生什么坐漏?",
                            "url": "http://www.reibang.com/p/45ba3e0d0c7e",
                            "image": "https://upload-images.jianshu.io/upload_images/3973862-d90954249a6f6ccd.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1000/format/webp",
                            "content": "打開瀏覽器從輸入網(wǎng)址到網(wǎng)頁(yè)呈現(xiàn)在大家面前,背后到底發(fā)生了什么碧信?經(jīng)歷怎么樣的一個(gè)過程赊琳?先給大家來張總體流程圖,具體步驟請(qǐng)看下文分..."
                        },
                        {
                            "title": "如何免翻墻使用谷歌搜索和Chrome應(yīng)用商店",
                            "url": "http://www.reibang.com/p/484f8e6c88f6",
                            "image": "https://upload-images.jianshu.io/upload_images/858154-015a4b083685a3d1.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/800/format/webp",
                            "content": "可能大家都聽過或正在使用谷歌瀏覽器砰碴,但是由于某種原因只能在谷歌瀏覽器使用百度搜索引擎躏筏,至于什么谷歌搜索引擎、谷歌商城呈枉、Gmail郵箱..."
                        },
                        {
                            "title": "四款前所未有好用的黑科技APP趁尼,絕對(duì)的良心實(shí)用,趕緊告訴家人",
                            "url": "http://www.reibang.com/p/2aec84d269fe",
                            "image": "https://upload-images.jianshu.io/upload_images/16042993-168b2cb17fd7ec0c?imageMogr2/auto-orient/strip%7CimageView2/2/w/640/format/webp",
                            "content": "手機(jī)微信猖辫、支付寶酥泞、淘寶等應(yīng)用都是我們經(jīng)常會(huì)使用到的APP,除此之外啃憎,我們就來就給大家?guī)韼卓罡佑腥ず猛娴暮诳萍糀PP芝囤,絕對(duì)的良心實(shí)用..."
                        },
                        {
                            "title": "堅(jiān)持學(xué)英語的方法有哪些",
                            "url": "http://www.reibang.com/p/0a6a61b0933c",
                            "image": "https://upload-images.jianshu.io/upload_images/3525704-c7293758fc59e56b.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/960/format/webp",
                            "content": "學(xué)習(xí)英語沒有什么捷徑,至少我認(rèn)為辛萍,我一直以來都是自學(xué)英語悯姊,從沒有聽過課堂上老師是怎么講英語的,都是通過聽廣播和看視頻學(xué)會(huì)的叹阔。我想說..."
                        }
                    ],
                    flag : false,
                },
                methods: {
                    search: function() {
                        this.flag =! this.flag;
                    }
                },
                computed: {
                    // 計(jì)算函數(shù)挠轴,匹配搜索
                    filteredArticles: function() {
                        var articles_array = this.articles,
                            searchString = this.searchString;
                        //搜索關(guān)鍵詞為空,則返回原始數(shù)據(jù)集
                        if (!searchString) {
                            return articles_array;
                        }
                        //搜索關(guān)鍵詞去除無用空格,轉(zhuǎn)換為小寫
                        searchString = searchString.trim().toLowerCase();
                        //過濾數(shù)組中每個(gè)元素,如果
                        articles_array = articles_array.filter(function(item) {
                            if (item.title.toLowerCase().indexOf(searchString) !== -1 ) {
                                return item;
                            }
                        })
                        // 返回轉(zhuǎn)化后的數(shù)組
                        return articles_array;
                    },
                }
            })
        </script>
    </body>
</html>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市耳幢,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌欧啤,老刑警劉巖睛藻,帶你破解...
    沈念sama閱讀 217,509評(píng)論 6 504
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異邢隧,居然都是意外死亡店印,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,806評(píng)論 3 394
  • 文/潘曉璐 我一進(jìn)店門倒慧,熙熙樓的掌柜王于貴愁眉苦臉地迎上來按摘,“玉大人包券,你說我怎么就攤上這事§畔停” “怎么了溅固?”我有些...
    開封第一講書人閱讀 163,875評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)兰珍。 經(jīng)常有香客問我侍郭,道長(zhǎng),這世上最難降的妖魔是什么掠河? 我笑而不...
    開封第一講書人閱讀 58,441評(píng)論 1 293
  • 正文 為了忘掉前任亮元,我火速辦了婚禮,結(jié)果婚禮上唠摹,老公的妹妹穿的比我還像新娘爆捞。我一直安慰自己,他們只是感情好勾拉,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,488評(píng)論 6 392
  • 文/花漫 我一把揭開白布煮甥。 她就那樣靜靜地躺著,像睡著了一般望艺。 火紅的嫁衣襯著肌膚如雪苛秕。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,365評(píng)論 1 302
  • 那天找默,我揣著相機(jī)與錄音艇劫,去河邊找鬼。 笑死惩激,一個(gè)胖子當(dāng)著我的面吹牛店煞,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播风钻,決...
    沈念sama閱讀 40,190評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼顷蟀,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了骡技?” 一聲冷哼從身側(cè)響起鸣个,我...
    開封第一講書人閱讀 39,062評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎布朦,沒想到半個(gè)月后囤萤,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,500評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡是趴,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,706評(píng)論 3 335
  • 正文 我和宋清朗相戀三年涛舍,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片唆途。...
    茶點(diǎn)故事閱讀 39,834評(píng)論 1 347
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡富雅,死狀恐怖掸驱,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情没佑,我是刑警寧澤毕贼,帶...
    沈念sama閱讀 35,559評(píng)論 5 345
  • 正文 年R本政府宣布,位于F島的核電站图筹,受9級(jí)特大地震影響帅刀,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜远剩,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,167評(píng)論 3 328
  • 文/蒙蒙 一扣溺、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧瓜晤,春花似錦锥余、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,779評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至足画,卻和暖如春雄驹,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背淹辞。 一陣腳步聲響...
    開封第一講書人閱讀 32,912評(píng)論 1 269
  • 我被黑心中介騙來泰國(guó)打工医舆, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人象缀。 一個(gè)月前我還...
    沈念sama閱讀 47,958評(píng)論 2 370
  • 正文 我出身青樓蔬将,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親央星。 傳聞我的和親對(duì)象是個(gè)殘疾皇子霞怀,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,779評(píng)論 2 354