Bootstrap

vue selection table多选传值默认选中

1,修改页面

 2,点击关联灯具数据框,弹出多选的dialog默认选中已选中数据

 父组件部分代码

// 表单  
   <el-dialog
      :title="title"
      :visible.sync="_visible"
      width="22%"
      :action-type="actionType"
      :close-on-click-modal="false"
      @opened="handleOpend"
      @close="handleClosed"
    >

      <el-form
        v-if="_visible"
        ref="pointFrom"
        :model="pointFrom"
        label-width="120px"
        label-position="left"
      >
        <el-col>
          <el-form-item label="点位编号:" prop="pointNum">
            <el-input v-model="pointFrom.pointNum" />
          </el-form-item>
          <el-form-item label="点位名称:" prop="pointName">
            <el-input v-model="pointFrom.pointName" />
          </el-form-item>
          <el-form-item label="坐标:" prop="lng">
            <span style="margin-right:10px;">{{ pointFrom.lng }},{{ pointFrom.lat }}</span>
            <el-button @click="showPickerDialog=true">拾取坐标</el-button>
          </el-form-item>
          <el-form-item label="关联报警柱">
            <el-select v-model="pointFrom.alarm.alarmName" clearable placeholder="请选择报警柱" @click.native="selectAlarm" @clear="clearAlarm" />
          </el-form-item>
          <el-form-item label="关联灯具">
            <el-select v-model="lightingDataNameList" multiple placeholder="请选择灯具" @click.native="selectLighting" @remove-tag="removeLightingTag" />
          </el-form-item>
          <el-form-item label="关联相机">
            <el-select v-model="videoSurveillanceNameList" multiple placeholder="请选择相机" @click.native="selectVideoSurveillance" @remove-tag="removeVideoSurveillanceTag" />
          </el-form-item>
        </el-col>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClosed">取 消</el-button>
        <el-button
          type="primary"
          @click="submitForm('pointFrom')"
        >确 定</el-button>
      </span>
    </el-dialog>


// 子组件  
<!-- 选择灯具 -->
    <select-Lighting
      :alarm-visible.sync="lightingVisible"
      :lighting-list.sync="lightingList"
      @lighting-data="lightingData"
    />

// 导入组件
import selectLighting from './select-lighting.vue'

export default {
 // 初始化页面
  components: {
    selectLighting
  },

// 相关参数
lightingVisible: false,
lightingDataNameList: [],
lightingList: [],

// 其他判断
  title() {
      switch (this.actionType) {
        case 'add':
          return '添加点位'
        case 'edit':
          return '修改点位'
        default:
          return ''
      }
    },

    _visible: {
      get() {
        return this.dialogVisible
      },
      set(val) {
        this.$emit('update:dialogVisible', val)
      }
    }
  },

 methods: {
// 初始化数据
 handleOpend() {
      this.$refs['pointFrom'].clearValidate()
      this.lightingData(this.pointFrom.lightingList)
    },

  handleClosed() {
      this._visible = false
      this.lightingDataNameList = []
      this.lightingList = []
      this.videoSurveillanceNameList = []
      this.pointFrom.lightingList = []
    },

// 选择灯具
    selectLighting() {
      this.lightingVisible = true
    },

 // 清除灯具数据
    removeLightingTag(TagName) {
      this.lightingList.splice(this.lightingList.findIndex(item => item.lightingName === TagName), 1)
    },

  // 选择灯具数据
    lightingData(lightingData) {
      this.pointFrom.lightingList = []
      this.lightingDataNameList = []
      this.lightingList = []
      lightingData.map(item => {
        this.lightingDataNameList.push(item.lightingName)
        this.lightingList.push(item)
      })
    },

}

}

 子组件完整代码

/* 选择灯具 */
<template>
  <el-dialog
    :title="title"
    :visible.sync="_visible"
    :close-on-click-modal="false"
    :destroy-on-close="true"
    width="58%"
    append-to-body
    @closed="handleClosed"
    @open="handleOpend"
  >
    <!-- 搜索栏 -->
    <el-row>
      <el-form :inline="true" :model="searchMap">
        <el-form-item label="灯具编号:">
          <el-input v-model="searchMap.lightingNum" clearable size="mini" />
        </el-form-item>
        <el-form-item label="灯具名称:">
          <el-input v-model="searchMap.lightingName" size="mini" clearable />
        </el-form-item>
        <div style="float:right">
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-search"
            @click="onSearch"
          >搜索</el-button></div>
      </el-form>

    </el-row>
    <!-- 功能区 -->
    <el-table ref="lightingTable" :data="tableData" tooltip-effect="dark" style="width: 100%" @select="selectSingle" @row-click="rowChange" @selection-change="handleSelectionChange">
      <el-table-column
        type="selection"
        width="55"
      />
      <el-table-column
        type="index"
        label="序号"
        width="60"
        :index="indexMethod"
        align="center"
      />
      <el-table-column
        prop="lightingNum"
        label="灯具编号"
        align="center"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        prop="lightingName"
        label="灯具名称"
        align="center"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        prop="lightingStatusName"
        label="灯具状态"
        align="center"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="坐标" :show-overflow-tooltip="true">
        <template slot-scope="{row}">
          <span>{{ row.lng }},{{ row.lat }}</span>
        </template>
      </el-table-column>

    </el-table>
    <!-- 分页条 -->
    <div class="footer-container">
      <div class="pagination-container">
        <el-pagination
          :current-page="searchMap.pageNum"
          :page-sizes="savedPageSizes"
          :page-size="savedPageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClosed">取 消</el-button>
      <el-button @click="submit">确 定</el-button>
    </span>
  </el-dialog>
</template>
<script>

import { mapState } from 'vuex'
import { selectPage } from '@/api/alarm/lighting.js'
export default {
  name: 'SelectAlarm',
  props: ['alarmVisible', 'lightingList'],
  data() {
    return {
      tableData: [],
      searchMap: {
        lightingNum: null,
        lightingName: null,
        pageNum: 1,
        pageSize: null
      },
      total: 0,
      count: 0,
      queryLotObj: {},
      parkLotList: [],
      checkList: [],
      rows: []

    }
  },
  computed: {
    ...mapState({
      savedPageSize: state => state.page.tablePageSize,
      savedPageSizes: state => state.page.tablePageSizes,
      tableStyle: state => state.page.tableStyle
    }),
    title: {
      get() {
        return '可关联灯具'
      }
    },
    _visible: {
      get() {
        return this.alarmVisible
      },
      set(val) {
        this.$emit('update:alarmVisible', val)
      }
    }
  },
  created() {
    this.initData()
  },

  methods: {

    initData() {
      this.searchMap.pageSize = this.savedPageSize
      this.loadTable()
    },

    loadTable() {
      this.tableData = []
      this.count = 0
      selectPage(this.searchMap).then((res) => {
        res.items.map(item => {
          this.tableData.push(item)
        })
        this.total = res.total
      })
    },

    // 序号
    indexMethod(index) {
      index = (index + 1) + (this.searchMap.pageNum - 1) * this.searchMap.pageSize
      return index
    },

    handleOpend() {
      this.tableData = []
      this.count = 0
      selectPage(this.searchMap).then((res) => {
        res.items.map(item => {
          this.tableData.push(item)
          // 回显默认选中判断
          this.lightingList.map(lighting => {
            if (lighting.id === item.id) {
              this.$refs.lightingTable.toggleRowSelection(item, true)
            }
          })
        })
        this.total = res.total
      })
    },

    handleClosed() {
      this.checkList = []
      this.searchMap.pageNum = 1
      this._visible = false
    },

    // 选中发生变化
    handleSelectionChange(selection) {
      this.checkList = selection
    },

    // 当某一行被点击
    rowChange(row, column, event) {
      const selected = this.rows.length && this.rows.indexOf(row) !== -1
      this.checkList.push(row)
      this.$refs.lightingTable.toggleRowSelection(row, selected)
    },

    // 勾选Checkbox
    selectSingle(rows, row) {
      this.rows = rows
    },

    submit() {
      if (this.checkList == null || this.checkList.length < 0) {
        this.$message({
          type: 'warning',
          message: '请最少选择一条数据!'
        })
      } else {
        this.$emit('lighting-data', this.checkList)
        this._visible = false
      }
    },
    // 搜索按钮
    onSearch() {
      this.loadTable()
    },

    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.searchMap.pageSize = val
      this.$store.dispatch('setTablePageSize', val)
      this.loadTable()
    },

    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.searchMap.pageNum = val
      this.loadTable()
    }

  }

}

</script>

<style lang="scss">
.my-autocomplete {
  border: 1px solid #2181e3;
  li {
    color: #ffffff !important;
    border-bottom: 1px solid #cccccc;
      &:hover {
       background: #1B558B;
  }
  }

}
</style>

后端实体参考

点位

/**   
 * Copyright © 2021 eSunny Info. Tech Ltd. All rights reserved.
 * 
 * 功能描述:报警点位
 * @Package: com.byx.pingjiang.common 
 * @author: xing xing hao
 * @date: 2021年12月22日 下午3:44:16 
 */
package com.byx.pingjiang.common.entity;

import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.JoinColumn;

import com.byx.pingjiang.common.entity.jpa.BaseEntity;
import com.byx.pingjiang.common.entity.jpa.VideoSurveillance;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;

import lombok.Data;
import lombok.EqualsAndHashCode;

/**
 * @ClassName: Area
 * @Description:设备点位表
 * @author: xing xing hao
 * @date: 2021年12月22日 下午3:44:16
 */
@Data
@EqualsAndHashCode(callSuper = false)
@Entity
@Table(name = "POINT")
public class Point extends BaseEntity {

	private static final long serialVersionUID = 1L;

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Integer id;

	/**
	 * 点位编号
	 */
	private String pointNum;

	/**
	 * 点位名称
	 */
	private String pointName;

	/**
	 * 经度(高德坐标系)
	 */
	private String lng;

	/**
	 * 纬度(高德坐标系)
	 */
	private String lat;

	/**
	 * 灯具
	 */
	@JsonProperty
	@ManyToMany
	@JoinTable(name = "POINT_LIGHTING", joinColumns = @JoinColumn(name = "POINT_ID"), inverseJoinColumns = @JoinColumn(name = "LIGHTING_ID"))
	private List<Lighting> LightingList;

	public void replaceLightingList(List<Lighting> LightingList) {
		this.LightingList.clear();
		if (LightingList != null) {
			this.LightingList.addAll(LightingList);
		}
	}

	/**
	 * 监控相机
	 */
	@JsonProperty
	@ManyToMany
	@JoinTable(name = "POINT_VIDEO", joinColumns = @JoinColumn(name = "POINT_ID"), inverseJoinColumns = @JoinColumn(name = "VIDEO_ID"))
	private List<VideoSurveillance> videoSurveillanceList;

	public void replacevideoSurveillanceList(List<VideoSurveillance> videoSurveillanceList) {
		this.videoSurveillanceList.clear();
		if (videoSurveillanceList != null) {
			this.videoSurveillanceList.addAll(videoSurveillanceList);
		}
	}

	/**
	 * 报警柱
	 */
	@JsonIgnoreProperties(value = "point", allowSetters = true)
	@OneToOne(mappedBy = "point", cascade = CascadeType.REFRESH, orphanRemoval = true)
	private Alarm alarm;

}

逻辑出来:

	/**
	 * 新增编辑
	 * 
	 * @param point
	 */
	@Transactional
	public void saveOrUpdate(Point point) {
		if (point.getId() != null) { // 修改
			Point dataBase = pointRepo.findById(point.getId()).get();
			Point p = new Point();
			BeanUtils.copyProperties(dataBase, p);
			pointRepo.save(p);


			// 关联灯具
			List<Lighting> pageLightingList = point.getLightingList(); // 页面点位信息

			dataBase.replaceLightingList(pageLightingList);
			pointRepo.save(dataBase);

		} else { // 添加
			pointRepo.save(point);
			Point dataBase = pointRepo.findById(point.getId()).get();

			// 关联灯具
			List<Lighting> pageLightingList = point.getLightingList(); // 页面点位信息

			// 关联灯具
			dataBase.setLightingList(pageLightingList);
			pointRepo.save(dataBase);
		}

	}

;