• 037 商品详情01


    1.Thymeleaf

    (1)简介

    Thymeleaf是用来开发Web和独立环境项目的现代服务器端Java模板引擎。注意:是在服务器端进行渲染。

    Thymeleaf的主要目标是为您的开发工作流程带来优雅的自然模板 - HTML。可以在直接浏览器中正确显示,并且可以作为静态原型,从而在开发团队中实现更强大的协作。

    借助Spring Framework的模块,可以根据自己的喜好进行自由选择,可插拔功能组件,Thymeleaf是现代HTML5 JVM Web开发的理想选择 - 尽管它可以做的更多。

    Spring官方支持的服务的渲染模板中,并不包含jsp。而是Thymeleaf和Freemarker等,而Thymeleaf与SpringMVC的视图技术,及SpringBoot的自动化配置集成非常完美,几乎没有任何成本,你只用关注Thymeleaf的语法即可。

    (2)特点

    • 动静结合:Thymeleaf 在有网络和无网络的环境下皆可运行,即它可以让美工在浏览器查看页面的静态效果,也可以让程序员在服务器查看带数据的动态页面效果。这是由于它支持 html 原型,然后在 html 标签里增加额外的属性来达到模板+数据的展示方式。浏览器解释 html 时会忽略未定义的标签属性,所以 thymeleaf 的模板可以静态地运行;当有数据返回到页面时,Thymeleaf 标签会动态地替换掉静态内容,使页面动态显示。

    • 开箱即用:它提供标准和spring标准两种方言,可以直接套用模板实现JSTL、 OGNL表达式效果,避免每天套模板、改jstl、改标签的困扰。同时开发人员也可以扩展和创建自定义的方言。

    • 多方言支持:Thymeleaf 提供spring标准方言和一个与 SpringMVC 完美集成的可选模块,可以快速的实现表单绑定、属性编辑器、国际化等功能。

    • 与SpringBoot完美整合,SpringBoot提供了Thymeleaf的默认配置,并且为Thymeleaf设置了视图解析器,我们可以像以前操作jsp一样来操作Thymeleaf。代码几乎没有任何区别,就是在模板语法上有区别。

    (3)基本用法

    参考笔记:https://www.cnblogs.com/luckyplj/p/11444967.html

    2.搭建商品详情页微服务

    商品详情浏览量比较大,并发高,我们会独立开启一个微服务,用来展示商品详情。

    (1)创建module

    商品的详情页服务,命名为:leyou-goods-web

     

    (2)pom文件

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <parent>
            <artifactId>leyou</artifactId>
            <groupId>lucky.leyou.parent</groupId>
            <version>1.0-SNAPSHOT</version>
        </parent>
        <modelVersion>4.0.0</modelVersion>
    
        <groupId>lucky.leyou.goods</groupId>
        <artifactId>leyou-goods-web</artifactId>
    
        <dependencies>
            <!--要给页面提供数据,要用到web-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <!--每一个独立的微服务都需要有eureka的启动器-->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
            </dependency>
            <!--本微服务需要调用其他微服务,需要用到feign-->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-openfeign</artifactId>
            </dependency>
            <!--thymeleaf的启动器-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-thymeleaf</artifactId>
            </dependency>
    
            <dependency>
                <groupId>lucky.leyou.item</groupId>
                <artifactId>leyou-item-interface</artifactId>
                <version>1.0-SNAPSHOT</version>
            </dependency>
    
            <!--测试类的启动器-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
            </dependency>
    
            <dependency>
                <groupId>lucky.leyou.common</groupId>
                <artifactId>leyou-common</artifactId>
                <version>1.0-SNAPSHOT</version>
            </dependency>
        </dependencies>
    </project>

    (3)application.yml文件

    server:
      port: 8084
    spring:
      application:
        name: goods-web
      thymeleaf:
        cache: false
    eureka:
      client:
        service-url:
          defaultZone: http://127.0.0.1:10086/eureka
        registry-fetch-interval-seconds: 5 #设置拉取微服务的时间
      instance:
        lease-renewal-interval-in-seconds: 5 # 每隔5秒发送一次心跳
        lease-expiration-duration-in-seconds: 10 # 10秒不发送就过期

    (4)编写启动类

    package lucky.leyou;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
    import org.springframework.cloud.openfeign.EnableFeignClients;
    
    @SpringBootApplication  //入口类Application的启动注解
    @EnableDiscoveryClient //能够让注册中心能够发现,扫描到该微服务
    @EnableFeignClients // 开启feign客户端
    public class LeyouGoodsWebApplication {
        public static void main(String[] args) {
            SpringApplication.run(LeyouGoodsWebApplication.class, args);
        }
    }

    (5)页面模板

    我们从leyou-portal中复制item.html模板到当前项目resource目录下的templates中。

    修改html:引入thymeleaf

    <html lang="en" xmlns:th="http://www.thymeleaf.org">

    初期模块结构图:

    3.页面跳转

    (1)修改页面跳转路径

    首先我们需要修改搜索结果页的商品地址,目前所有商品的地址都是:http://www.leyou.com/item.html

    我们应该跳转到对应的商品的详情页才对。

    那么问题来了:商品详情页是一个SKU?还是多个SKU的集合?

     

    通过详情页的预览,我们知道它是多个SKU的集合,即SPU。

    所以,页面跳转时,我们应该携带SPU的id信息。

    例如:http://www.leyou.com/item/2314123.html

    这里就采用了路径占位符的方式来传递spu的id,我们打开search.html,修改其中的商品路径:

                     <div class="p-img">
                                    <!--a标签内放置了商品的大图,并绑定了跳转的链接-->
                                    <!--需要动态渲染,用:href来替换原来的href-->
                                    <!--goods.id为spuid 查看后台search微服务的domain goods类可知-->
                                    <a :href="'item/'+goods.id+'.html'" target="_blank"><img :src="goods.selected.image" height="200"/></a>
                                    <ul class="skus">
                                        <!--若sku的id等于goods.selected选中的id,则去渲染这个样式,@mouseOver鼠标移动事件-->
                                        <li :class="{selected: goods.selected.id==sku.id}" v-for="(sku,j) in goods.skus" @mouseOver="goods.selected=sku"><img :src="sku.image"></li>
                                    </ul>
                                </div>

    刷新页面后再看:

    (2)编写跳转controller

    leyou-goods-web中编写controller,接收请求,并跳转到商品详情页:

    package lucky.leyou.controller;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    @Controller
    @RequestMapping("item")
    public class GoodsController {
    
        /**
         * 跳转到商品详情页
         * @param model 利用model传递数据到前端工程
         * @param id
         * @return
         */
        @GetMapping("{id}.html")
        public String toItemPage(Model model, @PathVariable("id")Long id){
    
            return "item"; //返回视图名称
        }
    }

    (3)nginx反向代理

    接下来,我们要把这个地址指向我们刚刚创建的服务:leyou-goods-web,其端口为8084

    我们在nginx.conf中添加一段逻辑:

    gzip  on;
        server {
            listen       80;
            server_name  www.leyou.com;
    
            proxy_set_header X-Forwarded-Host $host;
            proxy_set_header X-Forwarded-Server $host;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    
            location /item {
                proxy_pass http://127.0.0.1:8084;
                proxy_connect_timeout 600;
                proxy_read_timeout 600;
            }
    
        location / {
                proxy_pass http://127.0.0.1:9002;
                proxy_connect_timeout 600;
                proxy_read_timeout 600;
            }
        }

    配置代码说明:

    把以/item开头的请求,代理到我们的8084端口。

    重启Nginx

    nginx -s reload

    (4)测试

    启动leyou-goods-web这个微服务,点击搜索页面商品,看是能够正常跳转:

     

    (5)逻辑分析图

    4.封装数据模型

    首先我们一起来分析一下,在这个页面中需要哪些数据

    我们已知的条件是传递来的spu的id,我们需要根据spu的id查询到下面的数据:

    • spu信息

    • spu的详情

    • spu下的所有sku

    • 品牌

    • 商品三级分类

    • 商品规格参数、规格参数组

    (1)商品微服务(即leyou-item模块)提供接口

    <1>查询spu

    以上所需数据中,根据id查询spu的接口目前还没有,我们需要在商品微服务中提供这个接口:

    GoodsController:

    /**
         * 根据spuid查询spu
         * @param id spuid
         * @return
         */
        @GetMapping("spu/{id}")
        public ResponseEntity<Spu> querySpuById(@PathVariable("id") Long id){
            Spu spu = this.goodsService.querySpuById(id);
            if(spu == null){
                return new ResponseEntity<>(HttpStatus.NOT_FOUND);
            }
            return ResponseEntity.ok(spu);
        }

    IGoodsService及GoodsServiceImpl

     /**
         * 根据spuid查询spu
         * @param id spuid
         * @return
         */
        @Override
        public Spu querySpuById(Long id) {
            return this.spuMapper.selectByPrimaryKey(id);
        }

    GoodsApi:

    /**
         * 根据spu的id查询spu
         * @param id spuid
         * @return
         */
        @GetMapping("spu/{id}")
        public Spu querySpuById(@PathVariable("id") Long id);

    <2>查询规格参数组

    我们在页面展示规格时,需要按组展示:

    组内有多个参数,为了方便展示。我们在leyou-item-service中提供一个接口,查询规格组,同时在规格组内的所有参数。

    SpecificationController:

    /**
         * 根据分类id查询规格参数
         * @param cid
         * @return
         */
        @GetMapping("{cid}")
        public ResponseEntity<List<SpecGroup>> querySpecsByCid(@PathVariable("cid") Long cid){
            List<SpecGroup> list = this.specificationService.querySpecsByCid(cid);
            if(list == null || list.size() == 0){
                return new ResponseEntity<>(HttpStatus.NOT_FOUND);
            }
            return ResponseEntity.ok(list);
        }

    SpecificationServiceImpl:

    /**
         * 根据分类id查询规格参数
         * @param cid
         * @return
         */
        @Override
        public List<SpecGroup> querySpecsByCid(Long cid) {
            // 根据分类id查询分组,查询规格组
            List<SpecGroup> groups = this.queryGroupsByCid(cid);
            groups.forEach(g -> {
                // 查询组内参数
                g.setParams(this.queryParams(g.getId(), null, null, null));
            });
            return groups;
        }

    SpecificationAPI:

    package lucky.leyou.item.api;
    
    import lucky.leyou.item.domain.SpecGroup;
    import lucky.leyou.item.domain.SpecParam;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    
    import java.util.List;
    
    /**
     * 规格参数的接口:供feign使用
     */
    @RequestMapping("spec")
    public interface SpecificationApi {
    
        @GetMapping("params")
        public List<SpecParam> queryParams(
                @RequestParam(value = "gid", required = false) Long gid,
                @RequestParam(value = "cid", required = false) Long cid,
                @RequestParam(value = "generic", required = false) Boolean generic,
                @RequestParam(value = "searching", required = false) Boolean searching
        );
    
        // 查询规格参数组,及组内参数
        @GetMapping("{cid}")
        List<SpecGroup> querySpecsByCid(@PathVariable("cid") Long cid);
    
        @GetMapping("groups/{cid}")
        public List<SpecGroup> querySpecGroups(@PathVariable("cid") Long cid);
    
    }

    (2)创建FeignClient

    (3)封装数据模型

    我们创建一个GoodsService,在里面来封装数据模型。

    这里要查询的数据:

    • SPU

    • SpuDetail

    • SKU集合

    • 商品分类

      • 这里值需要分类的id和name就够了,因此我们查询到以后自己需要封装数据

    • 品牌对象

    • 规格组

      • 查询规格组的时候,把规格组下所有的参数也一并查出,上面提供的接口中已经实现该功能,我们直接调

    • sku的特有规格参数

    有了规格组,为什么这里还要查询?

    因为在SpuDetail中的SpecialSpec中,是以id作为规格参数id作为key,如图:

    但是,在页面渲染时,需要知道参数的名称,如图:

    我们就需要把id和name一一对应起来,因此需要额外查询sku的特有规格参数,然后变成一个id:name的键值对格式。也就是一个Map,方便将来根据id查找!

    <1>Service代码

    package lucky.leyou.service;
    
    import lucky.leyou.client.BrandClient;
    import lucky.leyou.client.CategoryClient;
    import lucky.leyou.client.GoodsClient;
    import lucky.leyou.client.SpecificationClient;
    import lucky.leyou.item.domain.*;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import java.util.*;
    
    @Service
    public class GoodsService {
    
        @Autowired
        private BrandClient brandClient;
    
        @Autowired
        private CategoryClient categoryClient;
    
        @Autowired
        private GoodsClient goodsClient;
    
        @Autowired
        private SpecificationClient specificationClient;
    
        public Map<String, Object> loadData(Long spuId){
            Map<String, Object> map = new HashMap<>();
    
            // 根据id查询spu对象
            Spu spu = this.goodsClient.querySpuById(spuId);
    
            // 根据spuid查询spudetail
            SpuDetail spuDetail = this.goodsClient.querySpuDetailById(spuId);
    
            // 查询sku集合
            List<Sku> skus = this.goodsClient.querySkuBySpuId(spuId);
    
            // 查询分类
            List<Long> cids = Arrays.asList(spu.getCid1(), spu.getCid2(), spu.getCid3());
            List<String> names = this.categoryClient.queryNameByIds(cids);
            List<Map<String, Object>> categories = new ArrayList<>();
            for (int i = 0; i < cids.size(); i++) {
                Map<String, Object> categoryMap = new HashMap<>();
                categoryMap.put("id", cids.get(i));
                categoryMap.put("name", names.get(i));
                categories.add(categoryMap);
            }
    
            // 查询品牌
            Brand brand = this.brandClient.queryBrandById(spu.getBrandId());
    
            // 查询规格参数组
            List<SpecGroup> groups = this.specificationClient.querySpecsByCid(spu.getCid3());
    
            // 查询特殊的规格参数
            List<SpecParam> params = this.specificationClient.queryParams(null, spu.getCid3(), null, false);
            Map<Long, String> paramMap = new HashMap<>();
            params.forEach(param -> {
                paramMap.put(param.getId(), param.getName());
            });
    
            // 封装spu
            map.put("spu", spu);
            // 封装spuDetail
            map.put("spuDetail", spuDetail);
            // 封装sku集合
            map.put("skus", skus);
            // 分类
            map.put("categories", categories);
            // 品牌
            map.put("brand", brand);
            // 规格参数组
            map.put("groups", groups);
            // 查询特殊规格参数
            map.put("paramMap", paramMap);
            return map;
        }
    }

    <2>然后在controller中把数据放入model:

    package lucky.leyou.controller;
    
    import lucky.leyou.service.GoodsService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    import java.util.Map;
    
    @Controller
    @RequestMapping("item")
    public class GoodsController {
        @Autowired
        private GoodsService goodsService;
    
        /**
         * 跳转到商品详情页
         * @param model 利用model传递数据到前端工程
         * @param id
         * @return
         */
        @GetMapping("{id}.html")
        public String toItemPage(Model model, @PathVariable("id")Long id){
            // 加载所需的数据
            Map<String, Object> modelMap = this.goodsService.loadData(id);
            // 放入模型
            model.addAllAttributes(modelMap);
            return "item"; //返回视图名称
        }
    }

    (4)页面测试数据

    我们在页面中先写一段JS,把模型中的数据取出观察,看是否成功:

    <script th:inline="javascript">
        const a = /*[[${groups}]]*/ [];
        const b = /*[[${params}]]*/ [];
        const c = /*[[${categories}]]*/ [];
        const d = /*[[${spu}]]*/ {};
        const e = /*[[${spuDetail}]]*/ {};
        const f = /*[[${skus}]]*/ [];
        const g = /*[[${brand}]]*/ {};
    </script>

    然后查看页面源码:

    5.渲染面包屑

    在商品展示页的顶部,有一个商品分类、品牌、标题的面包屑

    其数据有3部分:

    • 商品分类

    • 商品品牌

    • spu标题

    我们的模型中都有,所以直接渲染即可(页面101行开始):

           <!--面包屑部分-->
                <div class="crumb-wrap">
                    <ul class="sui-breadcrumb">
                        <!--会出现报错的红色波浪线,不去管他-->
                        <li th:each="category : ${categories}">
                            <a href="#" th:text="${category.name}">手机</a>
                        </li>
                        <li>
                            <a href="#" th:text="${brand.name}">Apple</a>
                        </li>
                        <li class="active" th:text="${spu.title}">Apple iPhone 6s</li>
                    </ul>
                </div>

    ctrl+shift+f9 刷新leyou-goods-web模块中的templates下的html页面

    浏览器中刷新页面进行测试:

    6.渲染商品列表

     先看下整体效果:

    这个部分需要渲染的数据有5块:

    • sku图片

    • sku标题

    • 副标题

    • sku价格

    • 特有规格属性列表

    其中,sku 的图片、标题、价格,都必须在用户选中一个具体sku后,才能渲染。而特有规格属性列表可以在spuDetail中查询到。而副标题则是在spu中,直接可以在页面渲染

    (1)副标题

    副标题是在spu中,所以我们直接通过Thymeleaf渲染:

    在第145行左右:

    <div class="news" th:utext="${spu.subTitle}"><span>推荐选择下方[移动优惠购],手机套餐齐搞定,不用换号,每月还有花费返</span></div>

    副标题中可能会有超链接,因此这里也用th:utext来展示,效果:

     

    Navicat打开数据库表:

    (2)渲染规格属性列表

    规格属性列表将来会有事件和动态效果。我们需要有js代码参与,不能使用Thymeleaf来渲染了。

    因此,这里我们用vue,不过需要先把数据放到js对象中,方便vue使用

    <1>初始化数据

    我们在页面的末尾中,定义一个js标签,然后在里面定义变量,保存与sku相关的一些数据:

    <script th:inline="javascript">
        // sku集合
        const skus = /*[[${skus}]]*/ [];
        // 规格参数id与name对
        const paramMap = /*[[${params}]]*/ {};
        // 特有规格参数集合
        const specialSpec = JSON.parse(/*[[${spuDetail.specialSpec}]]*/ "");
    </script>
    • specialSpec:这是SpuDetail中唯一与Sku相关的数据

      因此我们并没有保存整个spuDetail,而是只保留了这个属性,而且需要手动转为js对象。

    • paramMap:规格参数的id和name键值对,方便页面根据id获取参数名

    • skus:sku集合

    我们把刚才获得的几个变量保存在Vue实例中:

    我们来看下页面获取的数据:

     

     

    <2>通过Vue渲染

    <div id="specification" class="summary-wrap clearfix">
        <dl v-for="(v,k) in specialSpec" :key="k">
            <dt>
                <div class="fl title">
                    <i>{{paramMap[k]}}</i>
                </div>
            </dt>
            <dd v-for="(str,j) in v" :key="j">
                <a href="javascript:;" class="selected">
                    {{str}}<span title="点击取消选择">&nbsp;</span>
                </a>
            </dd>
        </dl>
    </div>

    然后刷新页面查看:

    数据成功渲染了。不过我们发现所有的规格都被勾选了。这是因为现在,每一个规格都有样式:selected,我们应该只选中一个,让它的class样式为selected才对!

    (3)规格属性的筛选

    规格参数的格式是这样的:

    每一个规格项是数组中的一个元素,因此我们只要保存被选择的规格项的索引,就能判断哪个是用户选择的了!

    我们需要一个对象来保存用户选择的索引,格式如下:

    {
        "4":0,
        "12":0,
        "13":0
    }

    但问题是,第一次进入页面时,用户并未选择任何参数。因此索引应该有一个默认值,我们将默认值设置为0。

    我们在head的script标签中,对索引对象进行初始化:

    然后在vue中保存:

    我们在页面中,通过判断indexes的值来判断当前规格是否被选中,并且给规格绑定点击事件,点击规格项后,修改indexes中的对应值:

    <div id="specification" class="summary-wrap clearfix">
        <dl v-for="(v,k) in specialSpec" :key="k">
            <dt>
                <div class="fl title">
                    <i>{{paramMap[k]}}</i>
                </div>
            </dt>
            <dd v-for="(str,j) in v" :key="j">
                <a href="javascript:;" :class="{selected: j===indexes[k]}" @click="indexes[k]=j">
                    {{str}}<span v-if="j===indexes[k]" title="点击取消选择">&nbsp;</span>
                </a>
            </dd>
        </dl>
    </div>

    效果图:

    (4)确定SKU

    在我们设计sku数据的时候,就已经添加了一个字段:indexes:

    这其实就是规格参数的索引组合。

    而我们在页面中,用户点击选择规格后,就会把对应的索引保存起来:

     

    因此,我们可以根据这个indexes来确定用户要选择的sku

    我们在vue中定义一个计算属性,来计算与索引匹配的sku:

    computed:{
        sku(){
            const index = Object.values(this.indexes).join("_");
            return this.skus.find(s => s.indexes == index);
        }
    }

    在浏览器工具中查看:

    (5)渲染sku列表

    既然已经拿到了用户选中的sku,接下来,就可以在页面渲染数据了

    <1>标题和价格

    <2>图片列表

    商品图片是一个字符串,以,分割,页面展示比较麻烦,所以我们编写一个计算属性:images(),将图片字符串变成数组:

    computed: {
        sku(){
            const index = Object.values(this.indexes).join("_");
            return this.skus.find(s=>s.indexes==index);
        },
        images(){
            return this.sku.images ? this.sku.images.split(",") : [''];
        }
    },

    页面改造:

    <div class="zoom">
       <!--默认第一个预览-->
       <div id="preview" class="spec-preview">
          <span class="jqzoom">
             <img :jqimg="images[0]" :src="images[0]" width="400px" height="400px"/>
          </span>
       </div>
       <!--下方的缩略图-->
       <div class="spec-scroll">
          <a class="prev">&lt;</a>
          <!--左右按钮-->
          <div class="items">
             <ul>
                <li v-for="(image, i) in images" :key="i">
                   <img :src="image" :bimg="image" onmousemove="preview(this)" />
                </li>
             </ul>
          </div>
          <a class="next">&gt;</a>
       </div>
    </div>

    最终效果图:

    7.商品详情

    商品详情是HTML代码,我们不能使用 th:text,应该使用th:utext

    在页面的第444行左右:

    <!--商品详情-->
    <div class="intro-detail" th:utext="${spuDetail.description}">
    </div>

    最终展示效果:

     8.规格包装

    规格包装分成两部分:

    • 规格参数

    • 包装列表

    而且规格参数需要按照组来显示

    (1)规格参数

    最终的效果:

    后台传给template包下的item.html页面的model中有一个groups

    从spuDetail中取出genericSpec并取出groups:

    <script th:inline="javascript">
        // sku集合
        const skus = /*[[${skus}]]*/ [];
        // 规格参数id与name对
        const paramMap = /*[[${paramMap}]]*/ {};
        // 特有规格参数集合,JSON.parse,可将json字符串转换为json对象
        const specialSpec = JSON.parse(/*[[${spuDetail.specialSpec}]]*/ "");
        const genericSpec = JSON.parse(/*[[${spuDetail.genericSpec}]]*/ "");
    
        let groups= /*[[${groups}]]*/ [];
    
        //创建一个对象来保存用户选择的索引,并设置每一个key值对应的默认值为0
        const indexes={};
        Object.keys(paramMap).forEach(param=>indexes[param]=0);
    </script>

    把genericSpec引入到Vue实例:

    因为sku是动态的,所以我们编写一个计算属性,来进行值的组合:

    groups(){
        groups.forEach(group => {
            group.params.forEach(param => {
                if(param.generic){
                    // 通用属性,去spu的genericSpec中获取
                    param.v = this.genericSpec[param.id] || '其它';
                }else{
                    // 特有属性值,去SKU中获取
                    param.v = JSON.parse(this.sku.ownSpec)[param.id]
                }
            })
        })
        return groups;
    }

    然后在页面渲染:

    <div class="Ptable">
        <div class="Ptable-item" v-for="group in groups" :key="group.name">
            <h3>{{group.name}}</h3>
            <dl>
                <div v-for="p in group.params">
                    <dt>{{p.name}}</dt><dd>{{p.v + (p.unit || '')}}</dd>
                </div>
            </dl>
        </div>
    </div>

    (2)包装列表

    包装列表在商品详情中,我们一开始并没有赋值到Vue实例中,但是可以通过Thymeleaf来渲染

    <div class="package-list">
        <h3>包装清单</h3>
        <p th:text="${spuDetail.packingList}"></p>
    </div>

    最终效果:

     

     

  • 相关阅读:
    JSTL&EL
    Response
    HTTP、Request
    Tomcat、Servlet
    单片机概念及应用
    JQuery高级
    Jquery基础
    JavaScript
    HTML、CSS
    跟着文档学习gulp1.2创建任务(task)
  • 原文地址:https://www.cnblogs.com/luckyplj/p/11611222.html
Copyright © 2020-2023  润新知