基于vue开发的element-ui树形控件报错问题解决

Posted on 2017-11-14 13:17  Rh九尾鱼  阅读(2423)  评论(0编辑  收藏  举报

对没错,这次又是ElementUI的问题,在使用ElementUI中的 tree 树形控件时需要动态添加DOM元素,但是在使用文档中给出的案例的时候会报错。

案例:ElementUI树形控件 - 自定义节点内容

<el-tree
  :data="data4"
  :props="defaultProps"
  show-checkbox
  node-key="id"
  default-expand-all
  :expand-on-click-node="false"
  :render-content="renderContent">
</el-tree>

<script>
  let id = 1000;

  export default {
    data() {
      return {
        data4: [{
          id: 1,
          label: '一级 1',
          children: [{
            id: 4,
            label: '二级 1-1',
            children: [{
              id: 9,
              label: '三级 1-1-1'
            }, {
              id: 10,
              label: '三级 1-1-2'
            }]
          }]
        }, {
          id: 2,
          label: '一级 2',
          children: [{
            id: 5,
            label: '二级 2-1'
          }, {
            id: 6,
            label: '二级 2-2'
          }]
        }, {
          id: 3,
          label: '一级 3',
          children: [{
            id: 7,
            label: '二级 3-1'
          }, {
            id: 8,
            label: '二级 3-2'
          }]
        }],
        defaultProps: {
          children: 'children',
          label: 'label'
        }
      }
    },

    methods: {
      append(data) {
        const newChild = { id: id++, label: 'testtest', children: [] };
        if (!data.children) {
          this.$set(data, 'children', []);
        }
        data.children.push(newChild);
      },

      remove(node, data) {
        const parent = node.parent;
        const children = parent.data.children || parent.data;
        const index = children.findIndex(d => d.id === data.id);
        children.splice(index, 1);
      },

      renderContent(h, { node, data, store }) {
        return (
          <span style="flex: 1; display: flex; align-items: center; justify-content: space-between; font-size: 14px; padding-right: 8px;">
            <span>
              <span>{node.label}</span>
            </span>
            <span>
              <el-button style="font-size: 12px;" type="text" on-click={ () => this.append(data) }>Append</el-button>
              <el-button style="font-size: 12px;" type="text" on-click={ () => this.remove(node, data) }>Delete</el-button>
            </span>
          </span>);
      }
    }
  };
</script>

其中 renderContent 函数中返回的内容会报错,于是在网络上寻找答案,不然组件是不能使用的。

原来是缺少相应的依赖,因为 renderContent 方法用到了jsx语法,所以需要要引入babel的JSX解析器,把JSX转化成JS语法,这个工作会由babel自动完成。

解决办法:

step1:安装相应依赖。

npm install babel-plugin-transform-vue-jsx
npm install babel-helper-vue-jsx-merge-props
npm install babel-plugin-syntax-jsx

step2:配置插件

在 .babelrc 文件中配置插件

 

返回顶部