Vue.js:计算属性和过滤器

计算属性(computed),主要用于处理一些复杂逻辑。

基础例子

<div id="app">
  <p>原始字符串: {{ message }}</p>
  <p>计算后反转字符串: {{ reversedMessage }}</p>
</div>
 
<script>
var vm = new Vue({
  el: '#app',
  data: {
    message: 'Runoob!'
  },
  computed: {
    // 计算属性的 getter
    reversedMessage: function () {
      // `this` 指向 vm 实例
      return this.message.split('').reverse().join('')
    }
  }
})
</script>

computed vs methods

我们可以使用 methods 来替代 computed,效果上两个都是一样的,但是 computed 是基于它的依赖缓存,只有相关依赖发生改变时才会重新取值。而使用 methods ,在重新渲染的时候,函数总会重新调用执行。使用 computed 性能会更好,但是如果你不希望缓存,可以使用 methods 属性。

例1:购物车价格计算

<!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练习-计算购物车总价</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">结算</button>
            </div>
            
            <div class="price" v-if="settled">
                <p>您购买了{{totalCount}}件商品,需要支付总价为:{{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:搜索页面

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>Vue.js computed练习-搜索页面的实现</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="  请输入" 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: "",
                    // 数据模型
                    articles: [{
                            "title": "堪称神器的3款在线工具,你一定用得上!",
                            "url": "https://www.jianshu.com/p/e83e7999346b",
                            "image": "https://upload-images.jianshu.io/upload_images/11438996-56b25f32c9307b4b?imageMogr2/auto-orient/strip%7CimageView2/2/w/640/format/webp",
                            "content": "一款在线免费GIF编辑神器,提供在线GIF压缩、视频转GIF、GIF合成、GIF裁剪四个功能,用户无需安装任何插件就可以轻松的进行视频格式...",
                        },
                        {
                            "title": "经典面试题:从 URL 输入到页面展现到底发生什么?",
                            "url": "https://www.jianshu.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": "打开浏览器从输入网址到网页呈现在大家面前,背后到底发生了什么?经历怎么样的一个过程?先给大家来张总体流程图,具体步骤请看下文分..."
                        },
                        {
                            "title": "如何免翻墙使用谷歌搜索和Chrome应用商店",
                            "url": "https://www.jianshu.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,绝对的良心实用,赶紧告诉家人",
                            "url": "https://www.jianshu.com/p/2aec84d269fe",
                            "image": "https://upload-images.jianshu.io/upload_images/16042993-168b2cb17fd7ec0c?imageMogr2/auto-orient/strip%7CimageView2/2/w/640/format/webp",
                            "content": "手机微信、支付宝、淘宝等应用都是我们经常会使用到的APP,除此之外,我们就来就给大家带来几款更加有趣好玩的黑科技APP,绝对的良心实用..."
                        },
                        {
                            "title": "坚持学英语的方法有哪些",
                            "url": "https://www.jianshu.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": "学习英语没有什么捷径,至少我认为,我一直以来都是自学英语,从没有听过课堂上老师是怎么讲英语的,都是通过听广播和看视频学会的。我想说..."
                        }
                    ],
                    flag : false,
                },
                methods: {
                    search: function() {
                        this.flag =! this.flag;
                    }
                },
                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>
</html>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容