zoukankan      html  css  js  c++  java
  • 069——VUE中vuex之使用getters高效获取购物车商品总价

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>vuex之使用getters高效获取购物车商品总价</title>
        <script src="vue.js"></script>
        <script src="vuex.js"></script>
    </head>
    <body>
    <div id="demo">
        <lists></lists>
    </div>
    <script type="text/x-template" id="lists">
        <div>
            <table border="1">
                <tr>
                    <th>编号</th>
                    <th>名称</th>
                    <th>单价</th>
                    <th>数量</th>
                    <th>总计</th>
                </tr>
                <tr v-for="v in goods">
                    <td>{{v.id}}</td>
                    <td>{{v.title}}</td>
                    <td>{{v.price}}</td>
                    <td>{{v.num}}</td>
                    <td></td>
                </tr>
            </table>
            <h1>总价:{{totalPrice}}</h1>
        </div>
    </script>
    <script>
        let store = new Vuex.Store({
            state: {
                totalPrice: 100,
                goods: [
                    {id: 1, title: 'iphone7', price: 100, num: 2},
                    {id: 2, title: 'vivo20', price: 200, num: 2}
                ]
            },
            getters: {
                //获取商品总价:
                totalPrice: state => {
                    let totalPrice = 0;
                    state.goods.forEach((v) => {
                        totalPrice += v.price * v.num;
                    })
                    return totalPrice;
                }
            }
        });
        let lists = {
            template: '#lists',
            computed: {
                totalPrice() {
                    return this.$store.getters.totalPrice;
                },
                goods() {
                    return this.$store.state.goods;
                }
            }
        }
        new Vue({
            el: "#demo",
            store,
            components: {
                lists
            }
    
        });
    </script>
    </body>
    </html>
    

      

  • 相关阅读:
    js自动小轮播
    js字符串
    工资
    可是姑娘,你为什么要编程呢?
    程序猿媳妇儿注意事项
    js勾选时显示相应内容
    js点击显示隐藏
    js选项卡
    js数组
    js旋转V字俄罗斯方块
  • 原文地址:https://www.cnblogs.com/yiweiyihang/p/8372287.html
Copyright © 2011-2022 走看看