账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    求助 如何快速看懂一个vue电商项目
    • 惜顔(Blank)°2018-09-15 00:00
    • 11
    33
    0

    最近拿到一个外包写的vue全家桶电商项目并且还是响应式的,上面让我改,交接也没有,还是用pug模板写的dom。chrome的vue插件也不知道为啥不生效,Vue.config.devtools = true加了的,拿着代码看了两天都没什么头绪,各种嵌套太复杂了,复制了一下header里的代码,还有lodash这插件也没有用过 真的要跑路了感觉

    相关代码

    <template lang="pug">

    .header-box.mb15(:view-mode="headerProps.viewMode")
        router-link.row.top-aadd.flex.jc-center(
            :to="`/goodsDetails?productId=${_got('ADObject.top_area.0.productId')}`"
            ref="topaadd"
        )
            //- 顶部图片
                    .topbar.pr.z10(ref="topbar" :class="{naviFloating}")
            .mc.flex.between.bbox.bar-height.w-box
                ._left.flex
                    .main-left-width.mr15(v-show="headerProps.viewMode==0")
                    .flex.city-container.pr
                        span(:title="currentCity.name") {{currentCity.name|trim(6)}}
                        i.icon.i-down1.pr
                        CitySelector(@input="cityChangeHandler" :cityId="currentCity.id")
            
                    template(v-if="!login")
                        a.top-link.loginText(@click="tryLogin")      登录
                        |   |
                        router-link.top-link.loginText(to="/register")      注册
                    template(v-if="login")
                        router-link.top-link.userNameOnTop(to="/user" @click.prevent.native="to(`/user`)")
                            span.pr.uname
                                |   {{userInfo.info.username | strcut(11)}}
                                i.icon.i-down1.pr.offset-y-1.pl025
                            .in-box
                                .row.flex.lh18
                                    img(:src="userInfo.info.file")
                                    .__right.pl05.cl-grey800.lh18
                                        .cl-occ-orange-hover.wnw(@click="to('/user')")
                                            |    用户:
                                            b   {{userInfo.info.username}}
                                        .fz09.cl-occ-orange-hover(@click="_loginOut") 退出登录
                        router-link.top-link.signBtn(to="/user/opower")      <i class="float-effect"></i>每日签到
                .right-box
                    .nav-list.flex
                        template(v-if="isDebug")
                            router-link.top-link(to="/home") 首页
                            router-link.top-link(to="/goods") 全部商品
                            router-link.top-link(to="/building") 应用下载
                            router-link.top-link(to="/chat/index") 乐言社区
                            a.top-link(href='http://web.occ-cn.com/join.html' target="_blank") 联系我们
                        template(v-if="!isDebug")
                            router-link.top-link(to="/home") 首页
                            router-link.top-link(to="/user/orderList") 我的订单
                            router-link.top-link(to="/chat/index") 乐言社区
                            router-link.top-link(to="/user/info") 万乐会员
                            router-link.top-link(to="/user/service") 客户服务
                            a.top-link(href='http://web.occ-cn.com/join.html' target="_blank") 联系我们
            
        .navi-in-view-placeholder.pr.offset-y-1(:id="`naviInViewPlaceholder_${_uid}`")
        .mc.pr.z100
            //.bar-height(v-show="headerProps.viewMode==1")
            LMenu.z100(
                ref="menu"
                :visible="menuVisible"
                @input="menuBeClick"
                @dataChange="menuDataChanged"
                :subCataId="$route.query.cataId||''"
                @reset="to('/')"
            )
        .bar-height(v-show="naviFloating")
    
        .search-bar-row
            .search-bar.row.flex.mc.between.mt15.ai-end.pr
                router-link.backToHomeLogo.pa(to="/home")
                ._left.flex.center
                    .main-left-width.mr30
                    input.pa.h1px.op00(ref="focuser")
                    el-autocomplete.flat-mode.long.mr10(
                        placeholder="请输入商品信息"
                        ref="autoComp"
                        icon="search"
                        v-model="input"
                        maxlength="180"
                        :fetchSuggestions="querySearchAsync"
                        :on-icon-click="handleIconClick"
                        @keydown.native.13="handleIconClick();$refs.autoComp.close()"
                        @select="handleSelect"
                    )
                    router-link.shopCartButton.pr.flex(
                        to="/cart" ,
                        @mouseover.native="cartShowState(true)" ,
                        @mouseout.native="cartShowState(false)"
                        ref="positionMsg"
                    )
                        i.icon.i-gouwucheman.cl-occ-orange.fz12
                        span.cl-occ-orange.pl05 我的预定
                        span.cart-num(:class="{longNumber:totalNum>99}")
                            i.num.cl-red(ref="num") ({{totalNum<100?totalNum:'99+'}})
                        // 购物车显示块
                        .nav-card-wrapper.pa.active(v-show="showCart && totalNum" ,@click.prevent="")
                            .nav-card-list.of.h(v-show="totalNum")
                                .ul.nav-cart-items
                                    router-link.cart-item.p15.bbox.flex(
                                        v-for="(item,i) in cartListPicked"
                                        :key="i"
                                        :to="'/goodsDetails?productId='+item.productId"
                                    )
                                        .item-thumb
                                            img(:src="item.productImg")
                                        .item-desc.fx1.ml15
                                            .cd.cl-grey700.fz15(v-text="item.productName")
                                            .mt15.flex.between
                                                ._l
                                                    span.fz12.cl-grey500   ¥
                                                    em.fz12.price-num.cl-grey800  {{item.salePrice}}
                                                    span.pl05.pr05.cl-grey500   x
                                                    em.fz12.cl-red.item-num    {{item.productNum}}
    
                                                ._r.flex.pr10
                                                    .cs(v-show="item.color") {{item.color}}/
                                                    .cs(v-show="item.size")  {{item.size}}
                                        .del-btn.del.of.h.hide-i(@click.stop="delGoods(item)") 删除
                                // 总件数
                                .nav-cart-total
                                    p   共 <strong>{{totalNum}}</strong>件商品
                                    h5  合计:<span class="price-icon">¥{{totalPrice}}</span>
                                    h6
                                        y-button.h30.w100p.m00.cl-grey50.lh30.main-btn(
                                            class-style="main-btn"
                                            style="height: 40px;width: 100%;margin: 0;color: #fff;font-size: 14px;line-height: 38px;"
                                            text="去购物车"
                                            @btnClick="tryLogin().then(()=>to(`/cart`))"
                                        )
                                .cart-con(v-show="!totalNum" style="height: 313px;text-align: center;")
                                    p 您的购物车竟然是空的!
                ._right
                    i.iico.sqcode.size96
                    .sqbtn.flex
                        i.iico.sqcode.size96
                        i.icon.i-erweima
                        |   扫码享优惠
    
    

    </template>
    <script>

    import {mapMutations, mapState} from 'vuex'
    import {getCartList, cartDel, getQuickSearch} from '/src/api/goods'
    import {loginOut} from '/api/index'
    import {setStore, getStore, removeStore} from '/utils/storage'
    import 'element-ui/lib/theme-default/index.css'
    import {menuList} from "/src/config"
    import LMenu from "/src/components/LMenu.vue"
    import daovoice from "/src/utils/daovoice"
    import {cataCacher, merchantCacher, productCacher, searchTipCacher} from "/src/utils/dataCacher"
    import {routeList} from "/src/utils/router.js";
    import inView from "in-view";
    import floatLayer from "/src/components/FloatLayer"
    import {brodcastMixin} from "/src/utils/globalMixin"
    import CitySelector from "/src/components/CitySelector";
    import {curretCityInfo} from "/src/utils/amap.util"
    import JMath from "/src/utils/JMath"
    
    let userNav = _.find(routeList, {name: "user"});
    userNav = userNav.children;
    userNav = userNav.filter(el => !el.hideinmenu);
    userNav = userNav.slice(0, 6);
    export default {
        components: {LMenu, floatLayer, CitySelector},
        mixins: [brodcastMixin],
        name: "header",
        data() {
            return {
                matchdCataId: "",
                user: {},
                // 查询数据库的商品
    
                //导航浮动
                st: false,
                // 头部购物车显示
                cartShow: false,
                positionL: 0,
                positionT: 0,
                timerCartShow: null, // 定时隐藏购物车
                input: '',
                timeout: null,
                token: '',
                userNav,
                menuList,
    
                menuVisible: true,
    
                //导航是否浮动状态
                naviFloating: false,
            }
        },
        computed: {
            headerProps() {
                return this.$store.state.headerProps
            },
            currentCata() {
                return this.$store.state.currentCata;
            },
            ...mapState([
                'cartList', 'login', 'receiveInCart', 'showCart', 'userInfo', "idDebug", "ADObject", "currentCity"
            ]),
            cartListPicked() {
                return _.compact(this.cartList || [])
            },
            // 计算价格
            totalPrice() {
                var totalPrice = 0
                this.cartListPicked.forEach(item => {
                    totalPrice += (item.productNum * item.salePrice)
                })
                return JMath.strip(totalPrice);
            },
            // 计算数量
            totalNum() {
                var totalNum = 0
                this.cartListPicked.forEach(item => {
                    totalNum += (item.productNum)
                })
                return JMath.strip(totalNum);
            }
        },
        methods: {
            ...mapMutations(['ADD_CART', 'INIT_BUYCART', 'ADD_ANIMATION', 'SHOW_CART', 'REDUCE_CART', 'RECORD_USERINFO', 'EDIT_CART']),
            menuDataChanged() {
                var m = this;
                m.$nextTick(() => {
                    if (!m.$refs || !m.$refs.menu || !m.$refs.menu.$el) return setTimeout(m.menuDataChanged, 333);
    
                    //计算菜单的高度
                    m.headerProps.menuHeight = m._got("$refs.menu.$el.offsetHeight");
                })
            },
    
            cityChangeHandler(city) {
                this.$store.commit('changeCity', city);
            },
    
            //选择分类导航菜单
            menuBeClick(cata) {
                var m = this;
                m.to("/goods", {cataId: cata.id})
            },
    
            //选择搜索建议
            handleSelect(item) {
                // this.input = item.value;
                this.input = "";
                this.to("/goodsDetails", {productId: item.productId})
            },
    
            //搜索按钮单击
            handleIconClick(ev) {
                this.to("/search", {key: this.input});
            },
    
    
            //搜索建议回调
            querySearchAsync(queryString, callback) {
                var m = this;
                if (!m._querySearchAsync) {
                    m._querySearchAsync = _.debounce(resp => {
                        m.input = m.input || ""
                        m.input = m.input.trim();
                        searchTipCacher.byId(m.input)
                            .then(ins => {
                                if (!ins) return [];
                                return ins.data;
                            })
                            .catch(() => [])
                            .then(callback)
                        ;
                    }, 210)
                }
                if (!m.input) return callback([]);
                m._querySearchAsync();
            },
    
            // 购物车显示
            cartShowState(state) {
                this.SHOW_CART({showCart: state})
            },
    
    
            //获取购物车
            _getCartList() {
                var m = this;
                getCartList(getStore('userId'))
                    .then(res => {
                        if (!res.success) throw res;
                        return Promise.all(
                            _.map(res.result, el => {
                                return productCacher.byId(el.productId)
                                    .then(pd => {
                                        //merchantCacher.save(pd.merchant)
                                        if (pd._status === 0) {
                                            throw "商品处于已下架状态";
                                        }
                                        el.merchantId = pd.merchantId;
                                        return el;
                                    })
                                    .catch(error => {
                                        util.consoleError(error);
                                        return null;
                                    })
                                    ;
                            })
                        ).then(resp => {
                            let ret = [];
                            _.compact(resp).forEach(pd=>{
                                let csLs = pd.colorSize;
                                delete pd.colorSize;
                                if(csLs && csLs.length){
                                    csLs.forEach(cs=>{
                                        let _pd = _.merge({},pd);
                                        _pd.productNum = cs.num;
                                        _pd.size=cs.size;
                                        _pd.color=cs.color;
                                        _pd.checked=cs.checked;
                                        ret.push(_pd)
                                    })
                                }
                            })
                            setStore('buyCart', ret)
                            this.INIT_BUYCART();
                        })
                        // 重新初始化一次本地数据
                    })
                    .catch(util.toastError)
                ;
            },
            // 删除商品
            delGoods({productId,color="",size=""}) {
                if (this.login) { // 登陆了
                    cartDel({userId: getStore('userId'), productId, color, size}).then(res => {
                        this.EDIT_CART({productId, color, size})
                    })
                } else {
                    this.EDIT_CART({productId, color, size})
                }
            },
    
            // 退出登陆
            _loginOut() {
                let params = {token: util.token()};
                io("/member/loginOut", "get", {params}).then(res => {
                    removeStore('buyCart');
                    store.commit("logout")
                    // this.to("/home")
                    location.href = "/"
                })
            },
        },
        mounted() {
            var m = this;
            this.token = getStore('token');
            m.rootOn("clearSearchInput", function () {
                m.input = "";
            })
            m.$watch("$route.query.key", key => {
                if (m.$route.path == "/search") {
                    m.input = key;
                }
            }, {})
    
    
            m.$watch("login", login => {
                if (login) {
                    this._getCartList();
                    let user = m.userInfo.info;
                    daovoice.popup(user.id, user.username, user.email, "");
                } else {
                    this.INIT_BUYCART()
                }
            }, {immediate: true})
    
            if (typeof (this.$route.query.key) !== undefined) {
                this.input = this.$route.query.key
            }
    
            let matchdCataIdFunction = _.debounce((cataData, cataId) => {
                cataCacher.byId(cataId).then(cata => {
                    m.$store.commit("currentCata", cata || "")
                })
            }, 150)
    
            m.unwatcherRecord = m.$watch("$store.state.cataData", cataData => {
                if (!cataData) {
                    return;
                }
    
                m.unwatcherRecord = m.$watch("$route.query.cataId", cataId => {
                    matchdCataIdFunction(cataData, cataId);
                }, {immediate: true})
            }, {immediate: true})
            //m.$watch("$store.state.currentCata",()=>matchdCataIdFunction(),{immediate:true});
    
            m.unwatcherRecord = m.$watch("$route.path", path => {
                if (
                    0
                    || path == "/home"
                    || path == "/goods"
                ) {
                    m.menuVisible = true;
                } else {
                    m.menuVisible = false;
                }
            }, {immediate: true});
    
            // m.$watch("")
            // m.headerProps.height = m.$el.offsetHeight - m._got("$refs.topaadd.offsetHeight",0);
    
            const calcHeight = _.debounce(() => {
                let vm = store.state.headerProps.viewMode;
                let offset = -m._got("$refs.topaadd.$el.offsetHeight", 0);
    
                if (vm != 0) {
                    offset -= m._got("$refs.topbar.offsetHeight", 0);
                }
    
                m.headerProps.height = m.$el.offsetHeight + offset;
                m.menuDataChanged();
            }, 150)
    
            m.$watch("$store.state.ADObject.top_area", calcHeight, {immediate: true});
            m.$watch("$store.state.headerProps.viewMode", calcHeight, {immediate: true})
            m.$watch("$store.state.cataData", calcHeight, {immediate: true})
            m.$watch("$route", calcHeight, {immediate: true, deep: true})
    
            //导航浮动相关代码
    
            let _idInView = `#naviInViewPlaceholder_${m._uid}`;
            inView(_idInView)
                .on('enter', el => {
                    m.naviFloating = false;
                })
                .on('exit', el => {
                    m.naviFloating = true;
                })
            ;
    
            m.naviFloating = !inView.is(document.querySelector(_idInView));
    
            curretCityInfo().then(console.log)
    
    
        },
    
        beforeDestroy() {
            var m = this;
        }
    }

    </script>
    <style lang="less" rel="stylesheet/less" scoped>

    @import "tool";
    @import "vars.less";
    @import "headr.less";

    </style>

    0
    打赏
    收藏
    点击回答
    您的回答被采纳后将获得:提问者悬赏的 11 元积分
        全部回答
    • 0
    更多回答
    扫一扫访问手机版

    回答动态

    师傅被妖怪抓走了:发布了悬赏问题火爆全网的“元宇宙”到底是什么?预计能赚取 1积分收益
    酒后略带风情:发布了悬赏问题Android内存中Graphics与Code占用过高预计能赚取 10积分收益
    扛起拖把扫天下:发布了悬赏问题typescript如何导出接口配置?求解,谢谢!预计能赚取 10积分收益
    发布了悬赏问题Vue 如何改变返回页面的路径?如让B页面只能返回到A页面.预计能赚取 11积分收益
    发布了悬赏问题vue H5移动端;底部bottom固定定位,安卓弹起键盘导致页面变形如何解决?预计能赚取 10积分收益
    发布了悬赏问题请问为什么tomcat8.5 GET请求中文正常,POST请求还需要设置UTF-8.预计能赚取 10积分收益
    发布了悬赏问题vue2.5+ts创建以及引入jq的方法预计能赚取 11积分收益
    情场浪女:发布了悬赏问题import ggplot时报错module 'pandas' has no attribute 'tslib'预计能赚取 10积分收益
    见心书画许老师18753375161:发布了悬赏问题echarts3 legend禁止点击事件,允许悬浮事件预计能赚取 11积分收益
    aa_92cb0bd09f:发布了悬赏问题codewar上的一个问题预计能赚取 11积分收益