繁体   English   中英

在vue中添加表中的列名和链接

[英]Adding the column name in the table and links in vue

我是初学者网络开发人员。 我在 Laravel 8 和 Vue 中制作了我的第一个 crud。 我在我的项目中使用了这个组件 t: https : //www.npmjs.com/package/vuejs-datatable

我有这个代码:

数据表.vue:

<template>
  <div>
    <div class="row mb-3">
      <div class="col-3">
        <div class="input-group">
          <input
            v-model="search"
            class="form-control"
            placeholder="Szukaj..."
            type="text"
          >
          <div class="input-group-append">
            <button class="btn btn-primary" type="button" @click.prevent="handleSearch">
              <font-awesome-icon icon="fas fa-search" />
            </button>
          </div>
        </div>
      </div>

      <div class="col-2">
        <div class="input-group">
          <label for="pageOption" class="mt-2 mr-2">Na stronie</label>
          <select class="form-control" v-model="perPage" @change="handlePerPage" id="pageOption">
            <option v-for="page in pageOptions" :key="page" :value="page">{{ page }}</option>
          </select>
        </div>
      </div>
    </div>


    <table class="table table-hover">
      <thead>
      <tr>
        <th class="table-head">#</th>
        <th v-for="column in columns" :key="column" @click="sortByColumn(column)"
            class="table-head">
          {{ column | columnHead }}
          <span v-if="column === sortedColumn">
                            <font-awesome-icon v-if="order === 'asc' "  icon="fas fa-angle-up" />
                            <font-awesome-icon v-else icon="fas fa-angle-down" />
            </span>
        </th>
      </tr>
      </thead>
      <tbody>
      <tr class="" v-if="tableData.length === 0">
        <td class="lead text-center" :colspan="columns.length + 1">Brak danych do wyświetlenia.</td>
      </tr>
      <tr v-for="(data, key1) in tableData" :key="data.id" class="m-datatable__row" v-else>
        <td>{{ serialNumber(key1) }}</td>
        <td v-for="(value, key) in data">{{ value }}</td>
      </tr>
      </tbody>
    </table>


  </div>
</template>

<script type="text/ecmascript-6">
import axios from 'axios';
import Vue from 'vue';
import 'vuejs-datatable/dist/themes/bootstrap-4.esm';
import {
  VuejsDatatableFactory,
  IDataFnParams,
  IDisplayHandlerParam,
  ITableContentParam,
  TColumnsDefinition,
  VueDatatable
} from 'vuejs-datatable';

Vue.use(VuejsDatatableFactory, VueDatatable);


export default {
  props: {
    fetchUrl: {type: String, required: true},
    columns: {type: Array, required: true},
  },
  data() {
    return {
      tableData: [],
      url: '',
      pagination: {
        meta: {to: 1, from: 1}
      },
      offset: 4,
      currentPage: 1,
      perPage: 1,
      sortedColumn: this.columns[0],
      order: 'asc',
      search: null,
      pageOptions: [1, 10, 20, 50],
    }
  },
  watch: {
    fetchUrl: {
      handler: function (fetchUrl) {
        this.url = fetchUrl
      },
      immediate: true
    }
  },
  created() {
    return this.fetchData()
  },
  computed: {
    /**
     * Get the pages number array for displaying in the pagination.
     * */
    pagesNumber() {
      if (!this.pagination.meta.to) {
        return []
      }
      let from = this.pagination.meta.current_page - this.offset
      if (from < 1) {
        from = 1
      }
      let to = from + (this.offset * 2)
      if (to >= this.pagination.meta.last_page) {
        to = this.pagination.meta.last_page
      }
      let pagesArray = []
      for (let page = from; page <= to; page++) {
        pagesArray.push(page)
      }
      return pagesArray
    },
    /**
     * Get the total data displayed in the current page.
     * */
    totalData() {
      return (this.pagination.meta.to - this.pagination.meta.from) + 1
    }
  },
  methods: {
    fetchData() {
      let dataFetchUrl = `${this.url}&page=${this.currentPage}&column=${this.sortedColumn}&order=${this.order}&per_page=${this.perPage}`
      axios.get(dataFetchUrl)
        .then(({data}) => {
          this.pagination = data
          this.tableData = data.data
        }).catch(error => this.tableData = [])
    },
    /**
     * Get the serial number.
     * @param key
     * */
    serialNumber(key) {
      return (this.currentPage - 1) * this.perPage + 1 + key
    },
    /**
     * Change the page.
     * @param pageNumber
     */
    changePage(pageNumber) {
      this.currentPage = pageNumber
      this.fetchData()
    },
    /**
     * Sort the data by column.
     * */
    sortByColumn(column) {
      if (column === this.sortedColumn) {
        this.order = (this.order === 'asc') ? 'desc' : 'asc'
      } else {
        this.sortedColumn = column
        this.order = 'asc'
      }
      this.fetchData()
    },
    handleSearch() {
      this.fetchData()
    },
    handlePerPage($event) {
      this.perPage = $event.target.value;
      this.fetchData()
    }
  },
  filters: {
    columnHead(value) {
      return value.split('_').join(' ').toUpperCase()
    }
  },
  translate: {
    nextButton: 'Dalej',
    previousButton: 'Wstecz',
    placeholderSearch: 'Szukaj...',
  },
  name: 'DataTable'
}
</script>

<style scoped>
</style>

笔记.vue:

<template>
  <CRow>
    <CCol col="12">
      <transition name="slide">
        <CCard>
          <CCardBody>
            <h4>
              Menus
            </h4>
            <CButton color="success" @click="createNote()" class="mb-3 my-5">Add Menu <font-awesome-icon icon="fas fa-plus" /> </CButton>
            <div class="flex-center position-ref full-height">
              <data-table
                :fetch-url="datatTableUrl"
                :columns="['name', 'email', 'id' , 'created_at']"
                :headers="['nazwa', 'adres email', 'ID' , 'utworzono']"
              ></data-table>
            </div>
          </CCardBody>
        </CCard>
      </transition>
    </CCol>
  </CRow>
</template>

<script>
import Vue from 'vue';

export default {
  data() {
    return {
      datatTableUrl: '',
    }
  },
  created: function () {
    this.datatTableUrl = Vue.prototype.$apiAdress + '/api/users/dataTable' + '?token=' + localStorage.getItem("api_token");
  },
  methods: {
    noteLink(id) {
      return `notes/${id.toString()}`
    },
    editLink(id) {
      return `notes/${id.toString()}/edit`
    },
    showNote(id) {
      const noteLink = this.noteLink(id);
      this.$router.push({path: noteLink});
    },
    editNote(id) {
      const editLink = this.editLink(id);
      this.$router.push({path: editLink});
    },
    deleteNote(id) {
      let self = this;
      let noteId = id;
      axios.post(this.$apiAdress + '/api/notes/' + id + '?token=' + localStorage.getItem("api_token"), {
        _method: 'DELETE'
      })
        .then(function (response) {
          self.message = 'Successfully deleted note.';
          self.showAlert();
          self.getNotes();
        }).catch(function (error) {
        console.log(error);
        self.$router.push({path: '/login'});
      });
    },
    createNote() {
      this.$router.push({path: 'notes/create'});
    },
  }
}
</script>

这段代码工作正常。

我有两个问题:

  1. 我希望表格中的列标题取自:标题 - 目前这些是来自数据库的列名(即:列)。

  2. 我想添加一个链接来编辑和删除记录。 我已经创建了方法:editLink()、deleteNote()。 如何将它们添加到我的表中? 我希望它们在“名称”列旁边可见

我怎样才能做到?

请帮我 :)

对于问题#1。 我会这样做。 将列和标题合并为一个对象,例如:其中键将是列名(重要:不要忘记注册标题道具)。

<data-table
     :fetch-url="datatTableUrl"
      :headers="{'name': 'nazwa','email': 'adres email','id': 'ID' , 'created_at': 'utworzono'}"
></data-table>

在数据表中:

<th v-for="(column, label) in headers" :key="column" @click="sortByColumn(column)" class="table-head">
          {{ label | columnHead }}
          <span v-if="column === sortedColumn">
                            <font-awesome-icon v-if="order === 'asc' "  icon="fas fa-angle-up" />
                            <font-awesome-icon v-else icon="fas fa-angle-down" />
            </span>
        </th>

对于第二个问题#2(不太清楚),最好将这些函数移动到数据表并将操作添加为新列,简短示例:

<td><button @click="editLink(key1)">Edit link or some fa fa icon</button></td>

在数据表中添加为道具:

props: {
    fetchUrl: {type: String, required: true},
    columns: {type: Array, required: true},
    headers: {type: Object, required: true} //<-- This
  },

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM