1、安装插件

npm i -S vuedraggable
import draggable from "vuedraggable";

2、封装子组件

<template>
  <el-popover>
    <el-button slot="reference" size="small">
      <i class="el-icon-s-tools"></i>
      <span>显示列</span>
    </el-button>
    <div>
      <draggable v-model="columns" :animation="150" @end="onEnd">
        <div v-for="item in columns" :key="item.id">
          <i class="el-icon-menu text-icon"></i>
          <el-checkbox
            :value="item.checked"
            @change="onCheckboxChange($event, item)"
          >
            {{ item.label }}
          </el-checkbox>
        </div>
      </draggable>
    </div>
  </el-popover>
</template>

<script>
import draggable from "vuedraggable";
export default {
  name: "TableColumn",
  components: { draggable },
  props: {
    value: {
      type: Array,
      require: true,
    },
  },
  data() {
    return {
      columns: this.value, // 使用 value 作为内部数据的初始值
    };
  },
  watch: {
    value(newValue) {
      // 当父组件传递的新值时,更新内部数据
      this.columns = newValue;
    },
  },
  methods: {
    //拖拽结束事件
    onEnd(val) {
       this.$emit("input", this.columns);
    },
    onCheckboxChange(checked, item) {
        console.log(checked);
      console.log(item);
      // checkbox 状态改变,更新对应项的 checked 属性
      item.checked = checked;
      // 触发事件,将更新后的数组传递给父组件
      this.$emit("input", this.columns);
    },
  },
};
</script>

<style>
.text-icon{
    margin-right: 10px;
    color: #585858;
}
</style>

3、父组件引用

父组件引用
import TableColumn from "@/components/TableColumn .vue";
components: { TableColumn },

页面调用
<table-column v-model="columns"></table-column>

父组件传值:
 columns: [
        {
          id: 1,
          label: "资产名称",
          prop: "type",
          checked: true,
          width: "200px",
        },
        { id: 2, label: "资产类型", prop: "name", checked: true },
        { id: 3, label: "资产版本", prop: "versionNo", checked: true },
        { id: 4, label: "资产IP", prop: "host", checked: true },
        { id: 5, label: "端口", prop: "port", checked: true },
        { id: 6, label: "资产编码", prop: "encoding", checked: true },
        { id: 7, label: "备注", prop: "remark", checked: true },
        { id: 8, label: "导入时间", prop: "createTime", checked: true },
      ],

4、最终效果
在这里插入图片描述

GitHub 加速计划 / vu / vue
207.54 K
33.66 K
下载
vuejs/vue: 是一个用于构建用户界面的 JavaScript 框架,具有简洁的语法和丰富的组件库,可以用于开发单页面应用程序和多页面应用程序。
最近提交(Master分支:2 个月前 )
73486cb5 * chore: fix link broken Signed-off-by: snoppy <michaleli@foxmail.com> * Update packages/template-compiler/README.md [skip ci] --------- Signed-off-by: snoppy <michaleli@foxmail.com> Co-authored-by: Eduardo San Martin Morote <posva@users.noreply.github.com> 4 个月前
e428d891 Updated Browser Compatibility reference. The previous currently returns HTTP 404. 5 个月前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐