5、計算屬性

計算屬性關鍵詞:computed

  • 以下代碼來說明methods方法和computed的區別
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>Vue.js computed 屬性練習</title>
        <!-- 通過CDN引入Vue.js -->
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    </head>
    <body>
        <!-- vue-app的根容器 -->
        <div id="app">
            <button type="button" @click="show">調用methods點擊</button>
            <button type="button" @click="git()">調用computed點擊</button>
        </div>
        <script type="text/javascript">
            /* 實例化一個Vue對象 */
            var app = new Vue({
                el: '#app',
                data: {
                    name1:'methods',
                    name2:'computed'
                },
                methods:{
                    show : function(){
                        alert(this.name1);
                        console.log(this.name1);
                    }
                    
                },
                computed:{
                    git:function(){
                        alert(this.name2);
                        console.log(this.name2);
                    }
                }
            })
        </script>
    </body>
</html>
  • 練習:購物車價格的計算
<!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">
        <!-- 通過CDN引入Vue.js -->
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
        <style type="text/css">
            .container {
                display: flex;
                flex-direction: column;
            }

            .item {
                display: flex;
                border: 1px solid #7FFFD4;
                border-radius: 0.625rem;
                width: 90%;
                margin: 0 auto;
                height: 80px;
                margin-bottom: 0.625rem;
                /* 垂直方向居中 */
                align-items: center;
                /* 水平方向居中 */
                /* justify-content: center; */
                padding-left: 0.625rem;
                padding-right: 0.625rem;
            }

            .item-id {
                flex: 1 1 10%;
                padding-left: 5px;
            }
            .item-ava{
                flex: 1 1 10%;
                
            }

            .item-name {
                flex: 1 1 30%;

            }

            .item-price {
                flex: 1 1 10%;
                padding-left:5px;
            }

            .item-count {
                /* display: flex; */
                flex: 1 1 30%;
                padding-left: 50px;

            }
            .btn1{
                background: white;
                border: 1px solid #EEEEEE;
            }

            .goods-count {
                width: 15px;
                text-align: center;
                margin-left: -5px;
                margin-right: -5px;
                border: none;
            }
            .total{
                display: flex;
                justify-content: space-between;
                align-items: center;
            }
            .btn{
                width: 20%;
                background-color: #FF5000;
                border-radius: 10px;
                border: none;
                outline: none;
                color: #FFF;
                font-size: 16px;
                
            }
            a:link{text-decoration: none; color: #333333;}
        </style>
    </head>
    <body>
        <!-- vue-app的根容器 -->
        <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.pic" width="30px" /></a>
                    </div>
                    <div class="item-name">
                        <a v-bind:href="goods.url">{{goods.name}}</a>
                    </div>
                    <div class="item-price">
                        {{goods.price}}
                    </div>
                    <div class="item-count">
                        <button type="button" @click="goods.count-=1" :disabled="goods.count==0" class="btn1">-</button>
                        <input type="text" class="goods-count" v-model="goods.count" />
                        <button type="button" @click="goods.count+=1" class="btn1">+</button>
                        <!-- <button type="button">詳情</button> -->
                    </div>
                </div>
                <hr>
                <div class="total">
                    <h3>總價: ¥{{totalPrice}}</h3>
                    <button type="button"  class="btn" @click="sum()">結算</button>
                </div>
                <div class="result" v-if="show">
                    <p>你購買了{{sum}}件商品,共花費了{{totalPrice}}</p>
                </div>
                
                
            </div>
        </div>
        <script type="text/javascript">
            /* 實例化一個Vue對象 */
            var app = new Vue({
                el: '#app',
                data: {
                    goodsList: [{
                            id: 1,
                            pic:'https://img.alicdn.com/imgextra/i2/2616970884/O1CN01pvNZIP1IOucAsZA7a_!!2616970884.jpg_430x430q90.jpg',
                            name: 'iPhone 8',
                            price: 6000,
                            count: 1,
                            url:'https://item.taobao.com/item.htm?spm=a230r.1.14.15.235e6715yEMgmH&id=584799309331&ns=1&abbucket=4#detail'
                        },
                        {
                            id: 2,
                            pic:'https://img.alicdn.com/imgextra/i1/2653126415/O1CN01zDJQqZ1xG7FxE83iZ_!!0-item_pic.jpg_430x430q90.jpg',
                            name: 'innisfree',
                            price: 100,
                            count: 2,
                            url:'https://detail.tmall.hk/hk/item.htm?spm=a230r.1.14.6.4bb431d1ZJCgvU&id=555700146877&cm_id=140105335569ed55e27b&abbucket=4'
                        },
                        {
                            id: 3,
                            pic:'https://img.alicdn.com/imgextra/i3/479940663/O1CN011Glh2GGL4zFDOI2_!!479940663.jpg_430x430q90.jpg',
                            name: '童裝',
                            price: 320,
                            count: 1,
                            url:'https://detail.tmall.com/item.htm?id=573629498709&ali_refid=a3_430583_1006:1103281714:N:%E9%A9%AC%E5%85%8Bjenny:ee00cf98898923c727825f2636c24d75&ali_trackid=1_ee00cf98898923c727825f2636c24d75&spm=a230r.1.14.1'
                        },
                        {
                            id: 4,
                            pic:'https://img.alicdn.com/imgextra/i1/2653126415/O1CN01zDJQqZ1xG7FxE83iZ_!!0-item_pic.jpg_430x430q90.jpg',
                            name: 'innisfree',
                            price: 500,
                            count: 1,
                            url:'https://detail.tmall.hk/hk/item.htm?spm=a230r.1.14.6.4bb431d1ZJCgvU&id=555700146877&cm_id=140105335569ed55e27b&abbucket=4'
                            }
                        

                    ],
                    show:false

                },
                methods: {
                },
                computed: {
                    totalPrice: function() {
                        //定義一個變量
                        var totalPrice = 0;
                        var len = this.goodsList.length;
                        for (var i = 0; i < len; i++) {
                            totalPrice += this.goodsList[i].price * this.goodsList[i].count;
                        }
                        return totalPrice;
                    },
                    sum: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>
</html>
下載.gif
  • 練習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">
        <!-- 通過CDN引入Vue.js -->
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
        <style type="text/css">
            .container {
                width: 90%;
                margin: 0 auto;
            }

            .input-box {
                width: 80%;
                height: 30px;
                margin-bottom: 15px;
                display: flex;

            }

            .article {
                display: flex;
                height: 80px;
                border: 1px solid #eee;
                border-radius: 8px;
                margin-bottom: 0.5rem;
            }

            .article-title {
                flex: 1 1 50%;
            }

            .article-thumbnail {
                flex: 1 1 30%;
            }

            .article-thumbnail img {
                width: 100%;
                height: 100%;
                border-radius: 10px;
            }

            a:link {
                text-decoration: none;
                color: #333333;
            }
            .search-box{
                width: 100%;
                
            }

            .search_btn {
                outline: none;
                width: 20%;
                height: 30px;
                margin-left: 10px;
                background: white;
                border: 1px solid #DDDDDD;
                
            }
        </style>
    </head>
    <body>
        <!-- vue-app的根容器 -->
        <div id="app">
            <div class="container">
                <div class="input-box">
                    <input type="text" v-model="searchString" placeholder="請輸入搜索內容" class="search-box" />
                    <button type="button" class="search_btn" >搜索</button>
                </div>
                <div class="article" v-for="article in filteredArticles">
                    <a :href="article.url" class="article-title">

                        {{article.title}}

                    </a>

                    <div class="article-thumbnail">
                        <a :href="article.url"><img :src="article.image" /></a>
                    </div>


                </div>

            </div>

        </div>
        <script type="text/javascript">
            var app = new Vue({
                el: '#app',
                data: {
                    searchString: "",
                    // 數據模型
                    articles: [{
                            "title": "堪稱神器的3款在線工具,你一定用得上!",
                            "url": "http://www.lxweimin.com/p/e83e7999346b",
                            "image": "https://upload-images.jianshu.io/upload_images/11438996-56b25f32c9307b4b?imageMogr2/auto-orient/strip%7CimageView2/2/w/640/format/webp"
                        },
                        {
                            "title": "經典面試題:從 URL 輸入到頁面展現到底發生什么?",
                            "url": "http://www.lxweimin.com/p/45ba3e0d0c7e",
                            "image": "https://upload-images.jianshu.io/upload_images/3973862-d90954249a6f6ccd.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1000/format/webp"
                        },
                        {
                            "title": "如何免翻墻使用谷歌搜索和Chrome應用商店",
                            "url": "http://www.lxweimin.com/p/484f8e6c88f6",
                            "image": "https://upload-images.jianshu.io/upload_images/858154-015a4b083685a3d1.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/800/format/webp"
                        },
                        {
                            "title": "四款前所未有好用的黑科技APP,絕對的良心實用,趕緊告訴家人",
                            "url": "http://www.lxweimin.com/p/2aec84d269fe",
                            "image": "https://upload-images.jianshu.io/upload_images/16042993-168b2cb17fd7ec0c?imageMogr2/auto-orient/strip%7CimageView2/2/w/640/format/webp"
                        },
                        {
                            "title": "堅持學英語的方法有哪些",
                            "url": "http://www.lxweimin.com/p/0a6a61b0933c",
                            "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>
</html>
下載 (1).gif
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容