使用jsx配置element-ui的table

背景

因爲表格數據比較同構,有時候列配置是動態的,此時但願使用v-for來配置columnhtml

<template>
<el-table :data="tableData">
  <el-table-column v-for="col in columns"
    :key="col.dataIndex"
    :label="col.title"
    :prop="col.dataIndex"
    :formatter="col.render" />
</el-table>
</template>

<script>
const PHONE_COLS = [
  { title: '錄音id', dataIndex: 'attach_id' },
  { title: '接聽客服', dataIndex: 'handle_user_info' },
  { title: '呼叫類型', dataIndex: 'type_desc' },
  { title: '通話時長', dataIndex: 'duration' },
];

const WORK_COLS = [
  { title: '工單id', dataIndex: 'attach_id' },
  { title: '建立客服', dataIndex: 'handle_user_info' },
  { title: '建立時間', dataIndex: 'c_t' },
  { title: '工單來源', dataIndex: 'source' },
  { title: '工單分類', dataIndex: 'ws_type',
    render: (row, column, cell) => (cell || []).join(',')
  }
];

export default {
  data () {
    return {
      columns: PHONE_COLS,
      tableData: [],
      tableTotal: 0,
    }
  },
}
</script>

能夠看到代碼比直接使用template更加簡潔,另外也能夠利用formatter函數處理簡單的自定義字符串vue

問題:自定義template的列

當咱們但願使用配置的方式來達到<template v-slot>的效果,須要藉助於vuerender函數與jsx模板node

jsx引入方法詳見 渲染函數 & JSX

此時全部想建立vnode的時候均可以藉助jsx來實現,jsx編譯須要一個createElement方法,以下react

// h就是createElement
function render(h) {
  var a = 'test'
  return (
    <el-tooltip class="item" effect="dark">
      {a}
    </el-tooltip>
  )
}

table的formatter方法也支持返回vnode渲染,所以咱們能夠想辦法拿到createElement後使用jsx來達到複雜列的渲染,以下git

<template>
<el-table :data="tableData">
  <el-table-column v-for="col in columns"
    :key="col.dataIndex"
    :label="col.title"
    :prop="col.dataIndex"
    :formatter="col.render" />
</el-table>
</template>

<script>
let createElement
const WORK_COLS = [
  { title: '工單id', dataIndex: 'attach_id' },
  { title: '建立客服', dataIndex: 'handle_user_info' },
  { title: '建立時間', dataIndex: 'c_t' },
  { title: '工單來源', dataIndex: 'source' },
  { title: '工單分類', dataIndex: 'ws_type',
    render: (row, column, cell) => (cell || []).join(',')
  },
  { title: '工單描述', dataIndex: 'desc',
    render: (row, column, cell) => {
      return (function(h) {
        return (
          <div domPropsInnerHTML={cell}></div>
        );
      })(createElement)
    }
  },
];

export default {
  data () {
    return {
      columns: WORK_COLS,
      tableData: [],
      tableTotal: 0,
    }
  },
  mounted() {
    createElement = this.$createElement
  }
}
</script>

說明github

  • 爲了使用jsx模板,咱們製造了帶有h函數的匿名函數來生成vnode
Note the h function, which is a shorthand for a Vue instance's $createElement method, must be in the scope where the JSX is. 詳細
  • 獲取createElement方法比較多,好比能夠把columns放在組件內部經過this.$createElement,此處是1個簡單例子
  • 咱們這裏的例子返回的是帶html特殊符號的字符串,須要使用innerHTML才能正確渲染,這裏react的dangerouslySetInnerHTML無效,須要使用babel-plugin-transform-vue-jsx的屬性domPropsInnerHTML

以上。babel

相關文章
相關標籤/搜索