第185天学习打卡(项目 谷粒商城27 JSR303自定义校验注解 SPU SKU 属性分组效果前端组件抽取 父子组件交互)

JSR303自定义校验注解

image-20210712100335853

gulimall-common valid

ListValue.java

package com.doudou.common.valid;

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;

@Documented
@Constraint(validatedBy = {ListValueConstraintValidator.class})
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ListValue {
    String message() default "{com.doudou.common.valid.ListValue.message}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
    int[] vals() default {};
}

ListValueConstraintValidator.java

package com.doudou.common.valid;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.HashSet;
import java.util.Set;

public class ListValueConstraintValidator implements ConstraintValidator<ListValue, Integer> {
    private Set<Integer> set = new HashSet<>();
    //初始化方法
    @Override
    public void initialize(ListValue constraintAnnotation) {
        int[] vals = constraintAnnotation.vals();
        //这里是进行非空判断
        for(int val : vals){
            set.add(val);
        }


    }
     //判断是否校验成功

    /**
     *
     * @param value 需要校验的值
     * @param Context
     * @return
     */
    @Override
    public boolean isValid(Integer value, ConstraintValidatorContext Context) {

        return set.contains(value);
    }
}

ValidationMessage.properties

com.doudou.common.valid.ListValue.message=必须提交指定的值

gulimall-product controller

BrandEntity .java

package com.doudou.gulimall.product.entity;

import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;

import java.io.Serializable;

import com.doudou.common.valid.AddGroup;
import com.doudou.common.valid.ListValue;
import com.doudou.common.valid.UpdateGroup;
import lombok.Data;
import org.hibernate.validator.constraints.URL;

import javax.validation.constraints.*;


/**
 * 品牌
 *
 * @author doudoutj111

 * @date 2021-06-19 17:24:02
 */
@Data
@TableName("pms_brand")
public class BrandEntity implements Serializable {
	private static final long serialVersionUID = 1L;

	/**
	 * 品牌id
	 */
	@NotNull(message = "修改必须指定品牌id", groups = {UpdateGroup.class})
	@Null(message = "新增不能指定id", groups = {AddGroup.class})
	@TableId
	private Long brandId;
	/**
	 * 品牌名
	 */
	@NotBlank(message = "品牌名必须提交", groups = {AddGroup.class, UpdateGroup.class})
	private String name;
	/**
	 * 品牌logo地址
	 */
	@NotBlank(groups = {AddGroup.class})
	@URL(message = "logo必须是一个合法的url地址",groups = {AddGroup.class, UpdateGroup.class})
	private String logo;
	/**
	 * 介绍
	 */
	private String descript;
	/**
	 * 显示状态[0-不显示;1-显示]
	 */
	@ListValue(vals={0,1}, groups = {AddGroup.class})
	private Integer showStatus;
	/**
	 * 检索首字母
	 */
	@NotEmpty(groups = {AddGroup.class})
	@Pattern(regexp = "/^[a-zA-Z]$/",message = "检索首字母必须是一个字母",groups = {AddGroup.class, UpdateGroup.class})
	private String firstLetter;
	/**
	 * 排序
	 */
	@NotNull(groups = {AddGroup.class})
	@Min(value = 0, message = "排序必须大于等于0",groups = {AddGroup.class, UpdateGroup.class})
	private Integer sort;

}

出现的错误 启动gulimallproduct之后测试输出的showStatus是乱码

解决办法

image-20210712095814022

image-20210712095937340

image-20210712095904578

image-20210712095741907

image-20210712095700612

image-20210712095612861

然后重启IDEA才会生效

image-20210712100022054

看某一个类的实现是在这个类上按快捷键是ctrl + h
检验前端时出现的错误 是后端正则表达式的错误

image-20210712211445558

修改正则表达式

image-20210712211604403

gulimall.product.entity

BrandEntity.java

package com.doudou.gulimall.product.entity;

import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;

import java.io.Serializable;

import com.doudou.common.valid.AddGroup;
import com.doudou.common.valid.ListValue;
import com.doudou.common.valid.UpdateGroup;
import lombok.Data;
import org.hibernate.validator.constraints.URL;

import javax.validation.constraints.*;


/**
 * 品牌
 *
 * @author doudoutj111

 * @date 2021-06-19 17:24:02
 */
@Data
@TableName("pms_brand")
public class BrandEntity implements Serializable {
	private static final long serialVersionUID = 1L;

	/**
	 * 品牌id
	 */
	@NotNull(message = "修改必须指定品牌id", groups = {UpdateGroup.class})
	@Null(message = "新增不能指定id", groups = {AddGroup.class})
	@TableId
	private Long brandId;
	/**
	 * 品牌名
	 */
	@NotBlank(message = "品牌名必须提交", groups = {AddGroup.class, UpdateGroup.class})
	private String name;
	/**
	 * 品牌logo地址
	 */
	@NotBlank(groups = {AddGroup.class})
	@URL(message = "logo必须是一个合法的url地址",groups = {AddGroup.class, UpdateGroup.class})
	private String logo;
	/**
	 * 介绍
	 */
	private String descript;
	/**
	 * 显示状态[0-不显示;1-显示]
	 */
	@ListValue(vals={0,1}, groups = {AddGroup.class})
	private Integer showStatus;
	/**
	 * 检索首字母
	 */
	@NotEmpty(groups = {AddGroup.class})
	@Pattern(regexp = "^[a-zA-Z]$",message = "检索首字母必须是一个字母",groups = {AddGroup.class, UpdateGroup.class})
	private String firstLetter;
	/**
	 * 排序
	 */
	@NotNull(groups = {AddGroup.class})
	@Min(value = 0, message = "排序必须大于等于0",groups = {AddGroup.class, UpdateGroup.class})
	private Integer sort;

}

image-20210712211820501

状态的检验

点击前端的显示状态出现的问题

{"msg":"参数格式校验失败","code":10001,"data":{"name":"品牌名必须提交"}}

image-20210712212026363

在gulimall-common valid 新建一个接口

image-20210712213352797

gulimall.product.controller

BrandController.java 中添加一个修改状态

package com.doudou.gulimall.product.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

//import org.apache.shiro.authz.annotation.RequiresPermissions;
import com.doudou.common.valid.AddGroup;
import com.doudou.common.valid.UpdateGroup;
import com.doudou.common.valid.UpdateStatusGroup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.doudou.gulimall.product.entity.BrandEntity;
import com.doudou.gulimall.product.service.BrandService;
import com.doudou.common.utils.PageUtils;
import com.doudou.common.utils.R;

import javax.validation.Valid;


/**
 * 品牌
 *
 * @author doudoutj111
 *
 * @date 2021-06-19 19:40:52
 */
@RestController
@RequestMapping("product/brand")
public class BrandController {
    @Autowired
    private BrandService brandService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    //@RequiresPermissions("product:brand:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = brandService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{brandId}")
   // @RequiresPermissions("product:brand:info")
    public R info(@PathVariable("brandId") Long brandId){
		BrandEntity brand = brandService.getById(brandId);

        return R.ok().put("brand", brand);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
  //  @RequiresPermissions("product:brand:save")
    public R save(@Validated({AddGroup.class}) @RequestBody BrandEntity brand/*, BindingResult result*/){
//        if(result.hasErrors()){
//            Map<String, String> map = new HashMap<>();
//            result.getFieldErrors().forEach((item)->{
//                //FieldError获取到错误信息
//                String message = item.getDefaultMessage();
//                //获取错误属性的名字
//                String field = item.getField();
//                map.put(field, message);
//
//
//
//            });
//            return  R.error(400,"提交的数据不合法").put("data", map);
//
//        }else{
//            brandService.save(brand);
//        }
        brandService.save(brand);


        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
  //  @RequiresPermissions("product:brand:update")
    public R update(@Validated(UpdateGroup.class) @RequestBody BrandEntity brand){
		brandService.updateById(brand);

        return R.ok();
    }

    /**
     * 修改状态
     */
    @RequestMapping("/update/status")
    //  @RequiresPermissions("product:brand:update")
    public R updateStatus(@Validated(UpdateStatusGroup.class) @RequestBody BrandEntity brand){
        brandService.updateById(brand);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
 //   @RequiresPermissions("product:brand:delete")
    public R delete(@RequestBody Long[] brandIds){
		brandService.removeByIds(Arrays.asList(brandIds));

        return R.ok();
    }

}

gulimall.product.entity

BrandEntity.java

package com.doudou.gulimall.product.entity;

import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;

import java.io.Serializable;

import com.doudou.common.valid.AddGroup;
import com.doudou.common.valid.ListValue;
import com.doudou.common.valid.UpdateGroup;
import com.doudou.common.valid.UpdateStatusGroup;
import lombok.Data;
import org.hibernate.validator.constraints.URL;

import javax.validation.constraints.*;


/**
 * 品牌
 *
 * @author doudoutj111

 * @date 2021-06-19 17:24:02
 */
@Data
@TableName("pms_brand")
public class BrandEntity implements Serializable {
	private static final long serialVersionUID = 1L;

	/**
	 * 品牌id
	 */
	@NotNull(message = "修改必须指定品牌id", groups = {UpdateGroup.class})
	@Null(message = "新增不能指定id", groups = {AddGroup.class})
	@TableId
	private Long brandId;
	/**
	 * 品牌名
	 */
	@NotBlank(message = "品牌名必须提交", groups = {AddGroup.class, UpdateGroup.class})
	private String name;
	/**
	 * 品牌logo地址
	 */
	@NotBlank(groups = {AddGroup.class})
	@URL(message = "logo必须是一个合法的url地址",groups = {AddGroup.class, UpdateGroup.class})
	private String logo;
	/**
	 * 介绍
	 */
	private String descript;
	/**
	 * 显示状态[0-不显示;1-显示]
	 */
	@NotNull(groups = {AddGroup.class, UpdateStatusGroup.class})
	@ListValue(vals={0,1}, groups = {AddGroup.class, UpdateStatusGroup.class})
	private Integer showStatus;
	/**
	 * 检索首字母
	 */
	@NotEmpty(groups = {AddGroup.class})
	@Pattern(regexp = "^[a-zA-Z]$",message = "检索首字母必须是一个字母",groups = {AddGroup.class, UpdateGroup.class})
	private String firstLetter;
	/**
	 * 排序
	 */
	@NotNull(groups = {AddGroup.class})
	@Min(value = 0, message = "排序必须大于等于0",groups = {AddGroup.class, UpdateGroup.class})
	private Integer sort;

}

前端添加一个路径

image-20210712213725000

image-20210712213817050

SPU 与SKU

image-20210712213842794

image-20210712213904715

基本属性【规格参数】与销售属性

image-20210712214040234

image-20210712214842832

image-20210712214953375

属性分组-效果 前端组件抽取

image-20210712215057847

image-20210712215533750

页面展示效果:

image-20210712215554236

接口文档地址:1、分页请求参数 (easydoc.net)

image-20210712220532239

attrgroup.vue

<!--  -->
<template>
  <el-row :gutter="20">
    <el-col :span="6">
      <category></category>
    </el-col>
    <el-col :span="18">
      <div class="mod-config">
        <el-form
          :inline="true"
          :model="dataForm"
          @keyup.enter.native="getDataList()"
        >
          <el-form-item>
            <el-input
              v-model="dataForm.key"
              placeholder="参数名"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button @click="getDataList()">查询</el-button>
            <el-button
              v-if="isAuth('product:attrgroup:save')"
              type="primary"
              @click="addOrUpdateHandle()"
              >新增</el-button
            >
            <el-button
              v-if="isAuth('product:attrgroup:delete')"
              type="danger"
              @click="deleteHandle()"
              :disabled="dataListSelections.length <= 0"
              >批量删除</el-button
            >
          </el-form-item>
        </el-form>
        <el-table
          :data="dataList"
          border
          v-loading="dataListLoading"
          @selection-change="selectionChangeHandle"
          style="width: 100%"
        >
          <el-table-column
            type="selection"
            header-align="center"
            align="center"
            width="50"
          >
          </el-table-column>
          <el-table-column
            prop="attrGroupId"
            header-align="center"
            align="center"
            label="分组id"
          >
          </el-table-column>
          <el-table-column
            prop="attrGroupName"
            header-align="center"
            align="center"
            label="组名"
          >
          </el-table-column>
          <el-table-column
            prop="sort"
            header-align="center"
            align="center"
            label="排序"
          >
          </el-table-column>
          <el-table-column
            prop="descript"
            header-align="center"
            align="center"
            label="描述"
          >
          </el-table-column>
          <el-table-column
            prop="icon"
            header-align="center"
            align="center"
            label="组图标"
          >
          </el-table-column>
          <el-table-column
            prop="catelogId"
            header-align="center"
            align="center"
            label="所属分类id"
          >
          </el-table-column>
          <el-table-column
            fixed="right"
            header-align="center"
            align="center"
            width="150"
            label="操作"
          >
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                @click="addOrUpdateHandle(scope.row.attrGroupId)"
                >修改</el-button
              >
              <el-button
                type="text"
                size="small"
                @click="deleteHandle(scope.row.attrGroupId)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          @size-change="sizeChangeHandle"
          @current-change="currentChangeHandle"
          :current-page="pageIndex"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          :total="totalPage"
          layout="total, sizes, prev, pager, next, jumper"
        >
        </el-pagination>
        <!-- 弹窗, 新增 / 修改 -->
        <add-or-update
          v-if="addOrUpdateVisible"
          ref="addOrUpdate"
          @refreshDataList="getDataList"
        ></add-or-update>
      </div>
    </el-col>
  </el-row>
</template>

<script>
//这里可以导入其他文件(比如:组件,工具js,第三方插件js,json文件,图片文件等等)
//例如:import 《组件名称》 from '《组件路径》';
import Category from "../common/category.vue";
import AddOrUpdate from './attrgroup-add-or-update'

export default {
  //import引入的组件需要注入到对象中才能使用
  components: { Category,AddOrUpdate },
  props: {},
  data() {
    return {
      dataForm: {
        key: "",
      },
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false,
    };
  },
   activated () {
      this.getDataList()
    },
    methods: {
      // 获取数据列表
      getDataList () {
        this.dataListLoading = true
        this.$http({
          url: this.$http.adornUrl('/product/attrgroup/list'),
          method: 'get',
          params: this.$http.adornParams({
            'page': this.pageIndex,
            'limit': this.pageSize,
            'key': this.dataForm.key
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.dataList = data.page.list
            this.totalPage = data.page.totalCount
          } else {
            this.dataList = []
            this.totalPage = 0
          }
          this.dataListLoading = false
        })
      },
      // 每页数
      sizeChangeHandle (val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle (val) {
        this.pageIndex = val
        this.getDataList()
      },
      // 多选
      selectionChangeHandle (val) {
        this.dataListSelections = val
      },
      // 新增 / 修改
      addOrUpdateHandle (id) {
        this.addOrUpdateVisible = true
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init(id)
        })
      },
      // 删除
      deleteHandle (id) {
        var ids = id ? [id] : this.dataListSelections.map(item => {
          return item.attrGroupId
        })
        this.$confirm(`确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/product/attrgroup/delete'),
            method: 'post',
            data: this.$http.adornData(ids, false)
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.getDataList()
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        })
      }
    }
};
</script>
<style  scoped>
</style>

category.vue

<!--  -->
<template>
 <el-tree
      :data="menus"
      :props="defaultProps"
      node-key="catId"
      ref="menuTree"
    >
     
    </el-tree>
</template>

<script>
//这里可以导入其他文件(比如:组件,工具js,第三方插件js,json文件,图片文件等等)
//例如:import 《组件名称》 from '《组件路径》';

export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  props: {},
  data() {
    //这里存放数据
    return {
      menus: [],
      expandedKey: [],
      defaultProps: {
        children: "children",
        label: "name",
      }
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
      getMenus() {
      this.$http({
        url: this.$http.adornUrl("/product/category/list/tree"),
        method: "get",
      }).then(({ data }) => {
        console.log("成功获取到菜单数据...", data.data);
        this.menus = data.data;
      });
    },
  },
  //生命周期 - 创建完成(可以访问当前this实例)
  created() {
      this.getMenus();
  },
  //生命周期 - 挂载完成(可以访问DOM元素)
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能,这个函数会触发
};
</script>
<style  scoped>
</style>

image-20210712224005297

页面展示效果

image-20210712224029284

父子组件交互

image-20210713081829583

category.vue

<!--  -->
<template>
 <el-tree
      :data="menus"
      :props="defaultProps"
      node-key="catId"
      ref="menuTree"
      @node-click="nodeclick"
    >
     
    </el-tree>
</template>

<script>
//这里可以导入其他文件(比如:组件,工具js,第三方插件js,json文件,图片文件等等)
//例如:import 《组件名称》 from '《组件路径》';

export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  props: {},
  data() {
    //这里存放数据
    return {
      menus: [],
      expandedKey: [],
      defaultProps: {
        children: "children",
        label: "name",
      }
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
      getMenus() {
      this.$http({
        url: this.$http.adornUrl("/product/category/list/tree"),
        method: "get",
      }).then(({ data }) => {
        console.log("成功获取到菜单数据...", data.data);
        this.menus = data.data;
      });
    },
    nodeclick(data,node,component){
      console.log("子组件category的节点被点击",data,node,component)

      //向父组件发送事件
      this.$emit("tree-node-click",data,node,component)


    }
  },
  //生命周期 - 创建完成(可以访问当前this实例)
  created() {
      this.getMenus();
  },
  //生命周期 - 挂载完成(可以访问DOM元素)
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能,这个函数会触发
};
</script>
<style  scoped>
</style>

attrgroup.vue

<!--  --><template>  <el-row :gutter="20">    <el-col :span="6">      <category @tree-node-click="treenodeclick"></category>    </el-col>    <el-col :span="18">      <div class="mod-config">        <el-form          :inline="true"          :model="dataForm"          @keyup.enter.native="getDataList()"        >          <el-form-item>            <el-input              v-model="dataForm.key"              placeholder="参数名"              clearable            ></el-input>          </el-form-item>          <el-form-item>            <el-button @click="getDataList()">查询</el-button>            <el-button              v-if="isAuth('product:attrgroup:save')"              type="primary"              @click="addOrUpdateHandle()"              >新增</el-button            >            <el-button              v-if="isAuth('product:attrgroup:delete')"              type="danger"              @click="deleteHandle()"              :disabled="dataListSelections.length <= 0"              >批量删除</el-button            >          </el-form-item>        </el-form>        <el-table          :data="dataList"          border          v-loading="dataListLoading"          @selection-change="selectionChangeHandle"          style="width: 100%"        >          <el-table-column            type="selection"            header-align="center"            align="center"            width="50"          >          </el-table-column>          <el-table-column            prop="attrGroupId"            header-align="center"            align="center"            label="分组id"          >          </el-table-column>          <el-table-column            prop="attrGroupName"            header-align="center"            align="center"            label="组名"          >          </el-table-column>          <el-table-column            prop="sort"            header-align="center"            align="center"            label="排序"          >          </el-table-column>          <el-table-column            prop="descript"            header-align="center"            align="center"            label="描述"          >          </el-table-column>          <el-table-column            prop="icon"            header-align="center"            align="center"            label="组图标"          >          </el-table-column>          <el-table-column            prop="catelogId"            header-align="center"            align="center"            label="所属分类id"          >          </el-table-column>          <el-table-column            fixed="right"            header-align="center"            align="center"            width="150"            label="操作"          >            <template slot-scope="scope">              <el-button                type="text"                size="small"                @click="addOrUpdateHandle(scope.row.attrGroupId)"                >修改</el-button              >              <el-button                type="text"                size="small"                @click="deleteHandle(scope.row.attrGroupId)"                >删除</el-button              >            </template>          </el-table-column>        </el-table>        <el-pagination          @size-change="sizeChangeHandle"          @current-change="currentChangeHandle"          :current-page="pageIndex"          :page-sizes="[10, 20, 50, 100]"          :page-size="pageSize"          :total="totalPage"          layout="total, sizes, prev, pager, next, jumper"        >        </el-pagination>        <!-- 弹窗, 新增 / 修改 -->        <add-or-update          v-if="addOrUpdateVisible"          ref="addOrUpdate"          @refreshDataList="getDataList"        ></add-or-update>      </div>    </el-col>  </el-row></template><script>/**父子组件传递数据1)子组件给父组件传递数据,事件机制   子组件给父组件发送一个事件,携带上数据   this.$emit(事件名,携带的数据...) *///这里可以导入其他文件(比如:组件,工具js,第三方插件js,json文件,图片文件等等)//例如:import 《组件名称》 from '《组件路径》';import Category from "../common/category.vue";import AddOrUpdate from './attrgroup-add-or-update'export default {  //import引入的组件需要注入到对象中才能使用  components: { Category,AddOrUpdate },  props: {},  data() {    return {      dataForm: {        key: "",      },      dataList: [],      pageIndex: 1,      pageSize: 10,      totalPage: 0,      dataListLoading: false,      dataListSelections: [],      addOrUpdateVisible: false,    };  },   activated () {      this.getDataList()    },    methods: {      //感知树节点被点击      treenodeclick(data,node,component){        console.log("attrgroup感知到category的节点被点击: ",data,node,component);        console.log("刚才被点击的菜单id: " ,data.catId)      },      // 获取数据列表      getDataList () {        this.dataListLoading = true        this.$http({          url: this.$http.adornUrl('/product/attrgroup/list'),          method: 'get',          params: this.$http.adornParams({            'page': this.pageIndex,            'limit': this.pageSize,            'key': this.dataForm.key          })        }).then(({data}) => {          if (data && data.code === 0) {            this.dataList = data.page.list            this.totalPage = data.page.totalCount          } else {            this.dataList = []            this.totalPage = 0          }          this.dataListLoading = false        })      },      // 每页数      sizeChangeHandle (val) {        this.pageSize = val        this.pageIndex = 1        this.getDataList()      },      // 当前页      currentChangeHandle (val) {        this.pageIndex = val        this.getDataList()      },      // 多选      selectionChangeHandle (val) {        this.dataListSelections = val      },      // 新增 / 修改      addOrUpdateHandle (id) {        this.addOrUpdateVisible = true        this.$nextTick(() => {          this.$refs.addOrUpdate.init(id)        })      },      // 删除      deleteHandle (id) {        var ids = id ? [id] : this.dataListSelections.map(item => {          return item.attrGroupId        })        this.$confirm(`确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {          confirmButtonText: '确定',          cancelButtonText: '取消',          type: 'warning'        }).then(() => {          this.$http({            url: this.$http.adornUrl('/product/attrgroup/delete'),            method: 'post',            data: this.$http.adornData(ids, false)          }).then(({data}) => {            if (data && data.code === 0) {              this.$message({                message: '操作成功',                type: 'success',                duration: 1500,                onClose: () => {                  this.getDataList()                }              })            } else {              this.$message.error(data.msg)            }          })        })      }    }};</script><style  scoped></style>

image-20210713083455629

B站学习网址:全网最强电商教程《谷粒商城》对标阿里P6/P7,40-60万年薪_哔哩哔哩_bilibili

posted @ 2021-07-12 22:43  豆豆tj  阅读(100)  评论(0)    收藏  举报