Vue extends拓展任意组件功能(el-select实例)-两种写法_el-select 拓展-程序员宅基地

技术标签: Vue拓展组件功能  vue  Vue  Vue extend  

用到ElementUI的select组件,要求能够多选并且重复选择。如果直接使用的话,首先el-tag会报错,因为循环中key值重复;其次,他的移除是通过indexof搜索移除的tag的值,且在remove-tag事件中未抛出被移除tag的索引,这样的后果是存在多个相同值的tag时,只会移除第一个相同值的tag

思路

el-tag的循环中,给close事件增加一个参数index,然后重写deleteTag方法,直接通过index删除该tag

  1. Vue: @close="deleteTag($event, item)"
  2. JSX: on-close={e => this.deleteTag(e, this.selected[0])}
deleteTag(event, tag, tagIndex){
    
  const value = this.value.slice();
  value.splice(tagIndex, 1);// 核心代码,其他代码省略
}

写法一、Vue template(推荐)

非常简单,改动特别少,可以使用Vue的所有用法,只需要复制el-select的template

  1. 新建一个vue文件
  2. 复制el-select的template模板内容过来
  3. 导入el-select,继承
  4. 覆盖methods中的deleteTag

结果

<template>
  <div
    class="el-select"
    :class="[selectSize ? 'el-select--' + selectSize : '']"
    @click.stop="toggleMenu"
    v-clickoutside="handleClose">
    我是示例代码,此处为自定义模板内容
  </div>
</template>

<script>
  import {
     Select} from 'element-ui';
  export default {
    
    extends: Select,//继承
    name: 'my-el-select',
    methods: {
    
      deleteTag(event, tag, tagIndex) {
    
// 重写该方法
    },
  },
  };
</script>

写法二、JSX(比较麻烦)

需要手动将Vue template转为jsx写法,无法使用事件修饰符,部分指令等等,改动比较大

1、导入继承

import {
    Select} from 'element-ui';

const myElSelect = {
    
  extends: Select
}

2、 重写render

Vue template最终编译之后也是生成render函数,这里覆盖render函数,
生成自定义内容。此处的意义只是为了记录以便于方便我用render函数时的jsx写法

render()
{
    
    const tagContent = () => {
    
      if (this.collapseTags && this.selected.length) {
    
        const tag0 = (
          <el-tag
            closable={
    !this.selectDisabled}
            size={
    this.collapseTagSize}
            hit={
    this.selected[0].hitState}
            type='info'
            on-close={
    e => this.deleteTag(e, this.selected[0])}
            disable-transitions={
    true}>
            <span class='el-select__tags-text'>{
    this.selected[0].currentLabel}</span>
          </el-tag>
        );
        const tag1 = (
          <el-tag
            closable={
    false}
            size={
    this.collapseTagSize}
            type='info'
            disable-transitions={
    true}>
            <span class='el-select__tags-text'>+ {
    this.selected.length - 1}</span>
          </el-tag>
        );

        if (this.selected.length > 1) {
    
          return (
            <span>
              {
    tag0}
              {
    tag1}
            </span>
          );
        }
        return (
          <span>
            {
    tag0}
          </span>
        );
      }
    };
    const emptyText = () => {
    
      if (this.emptyText && (!this.allowCreate || this.loading || (this.allowCreate && this.options.length === 0))) {
    
        return (
          <p class='el-select-dropdown__empty'>{
    this.emptyText}</p>
        );
      }
    };
    const selectOption = () => {
    
      return (
        <transition
          name='el-zoom-in-top'
          on-before-enter={
    this.handleMenuEnter}
          on-after-leave={
    this.doDestroy}>
          <el-select-menu
            ref='popper'
            append-to-body={
    this.popperAppendToBody}
            v-show={
    this.visible && this.emptyText !== false}>
            <el-scrollbar
              tag='ul'
              wrap-class='el-select-dropdown__wrap'
              view-class='el-select-dropdown__list'
              ref='scrollbar'
              class={
    {
    'is-empty': !this.allowCreate && this.query && this.filteredOptionsCount === 0}}
              v-show={
    this.options.length > 0 && !this.loading}>
              {
    this.showNewOption ? (
                <el-option
                  value={
    this.query}
                  created={
    true}>
                </el-option>
              ) : null}
              {
    
                this.$slots.default
              }
            </el-scrollbar>
            {
    emptyText()}
          </el-select-menu>
        </transition>
      );
    };
    return (
      <div
        class={
    ['el-select', this.selectSize ? 'el-select--' + this.selectSize : '']}
        on-click={
    this.toggleMenu} v-clickoutside={
    this.handleClose}>
        <div
          class='el-select__tags'
          ref='tags'
          style={
    {
    'max-width': this.inputWidth - 32 + 'px'}}>
          {
    tagContent()}
          <transition-group onAfterLeave={
    this.resetInputHeight}>
            {
    this.selected.map((item, index) => {
    
              return (
                <el-tag
                  key={
    index}
                  closable={
    !this.selectDisabled}
                  size={
    this.collapseTagSize}
                  hit={
    item.hitState}
                  type='info'
                  on-close={
    (e) => this.deleteTag(e, item, index)}
                  disable-transitions={
    false}>
                  <span class='el-select__tags-text'>{
    item.currentLabel}</span>
                </el-tag>
              );
            })}
          </transition-group>
        </div>
        <el-input
          ref='reference'
          value={
    this.selectedLabel}
          type='text'
          placeholder={
    this.currentPlaceholder}
          name={
    this.name}
          id={
    this.id}
          auto-complete={
    this.autoComplete}
          size={
    this.selectSize}
          disabled={
    this.selectDisabled}
          readonly={
    this.readonly}
          validate-event={
    false}
          class={
    {
    'is-focus': this.visible}}
          on-focus={
    this.handleFocus}
          on-blur={
    this.handleBlur}
          on-keyup_native={
    this.debouncedOnInputChange}
          on-paste_native={
    this.debouncedOnInputChange}
          on-mouseenter_native={
    (this.inputHovering = true)}
          on-mouseleave_native={
    (this.inputHovering = false)}
        >
          <i slot='suffix'
             class={
    ['el-select__caret', 'el-input__icon', 'el-icon-' + this.iconClass]}
             on-click={
    () => this.handleIconClick}/>
        </el-input>
        {
    selectOption()}
      </div>
    );
  }

3、 重写method里的deleteTag方法

4、结果

import {
    Select} from 'element-ui';

const myElSelect = {
    
  extends: Select,
  methods: {
    
    deleteTag(event, tag, tagIndex) {
    
     // *****略
    },
  },
  render() {
    
    return (
      <div>例子</div>
    );
  }
};
export default myElSelect;
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_31201781/article/details/101427594

智能推荐

VS2015 连接、查询SqlServer/_variant_t 与 std::string 相互转换__variant_t std::string-程序员宅基地

文章浏览阅读447次。以下代码在vs2015中测试通过,使用标准Windows库。连接SqlSerer和查询的代码是东拼西凑的,_variant_t 与 std::string 相互转换是自己翻书写的。_variant_t 如果是日期、整数等其他数据类型,会自动转成std::string,没有乱码。// SqlServerTest.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include <ICRSINT.H>#include <vector>#__variant_t std::string

java调用第三方dll文件-程序员宅基地

文章浏览阅读835次。网上调用第三方dll组件的方法有很多,作者是通过jna进行调用的,试过com组件封装但是组件,但是一直没有成功,因为是.net的dll文件(net.dll),故无法直接使用jna进行调用,所以作者的思路是将net.dll用c先引入后,再做成一个c的dll,供dll后改用jna调用c的dll,c的dll再调用原始的dll文件..._java调用第三方dll文件

网关神器Kong(一):介绍_kong网关-程序员宅基地

文章浏览阅读8.6k次,点赞5次,收藏36次。物联网网关神器 Kong ( 一 )当你看到这只大猩猩的时候,是不是感觉优点萌萌的。哈哈,这就是我们这篇文章要讲解的一个开源项目 – Kong( 云原生架构下的分布式API 网关 )。为什么说 Kong 是物联网网关神器?在 IOT 系统架构中,为了保证系统的鲁棒性和高可扩展性。我们需要一个强大的 API 网关来承受住遍布各地的 IOT 设备所传输的信息。插件架构设计的 Kong 使得它具有了强大的兼容性,和可扩展性。TCP 和 UDP原始流的支持,更是使得它可以适配多种协议,完美的解决了 IOT_kong网关

Element-UI 自定义upload组件(进度条,删除,下载)_el-upload自定义删除-程序员宅基地

文章浏览阅读755次。on-progress=“uploadFileProcess” //文件传输过程(处理进度条):show-file-list=“false” //自定义样式所以设置false不显示。:before-upload=“beforeUploadFile” //文件上传前。:on-success=“handleFileSuccess” //文件成功。:action=“uploadUrl” //文件上传的地址(必填):file-list=“fileArr”//文件列表。multiple//多文件上传。_el-upload自定义删除

Codec基础知识-程序员宅基地

文章浏览阅读2.2k次。Codec基础知识学习_codec

Postgresql创建用户与数据库并赋予权限_pgsql创建用户 数据库赋权-程序员宅基地

文章浏览阅读7.7k次。3、给iuser用户,创建数据库叫work_base。4.3、将work_base的所有权限赋予iuser。4、授予iuser当前work_base的全部权限。2、添加名为iuser的用户,并设置密码。1、使用postgres登录pgsql。4.1、 先退出postgre数据库。4.2、登录work_base数据库。_pgsql创建用户 数据库赋权

随便推点

2017二级c语言考试大纲,2017年计算机等级考试二级C语言程序设计考试大纲-程序员宅基地

文章浏览阅读66次。摘要全国计算机等级考试二级C 语言程序设计考试大纲(2013 年版)基本要求1. 熟悉Visual C++ 6. 0 集成开发环境。2. 掌握结构化程序设计的方法,具有良好的程序设计风格。3. 掌握程序设计中简单的数据结构和算法并能阅读简单的程序。4. 在Visual C++ 6. 0 集成环境下,能够编写简单的C 程序,并具有基本的纠错和调试程序的能力。考试内容一、C 语言程序的结构1. 程序的...

支付宝的骚操作。。-程序员宅基地

文章浏览阅读227次。前天的文章刚提到大家买基金的热情一路高涨:基金韭菜们太疯狂了!然后昨天我就在支付宝上面有了几个新的发现。支付宝作为一个支付金融工具,本来就是有理财属性的,在支付宝的App上面也有一个单独...

工作流-flowable_flowable工作流-程序员宅基地

文章浏览阅读1.9k次,点赞3次,收藏15次。1. 简单介绍工作流 2. 使用flowable和java api写一个demo 3. 使用flowable集合springboot写一个demo_flowable工作流

__attribute__ 你知多少?___attribute__是哪种变量-程序员宅基地

文章浏览阅读4.9k次,点赞9次,收藏47次。GNU C 的一大特色就是__attribute__ 机制。__attribute__ 可以设置函数属性(Function Attribute )、变量属性(Variable Attribute )和类型属性(Type Attribute )。__attribute__ 书写特征是:__attribute__ 前后都有两个下划线,并切后面会紧跟一对原括弧,括弧里面是相应的__attribu___attribute__是哪种变量

CDH5-mysql安装_安装cdh不安装mysql-程序员宅基地

文章浏览阅读730次。0.Change Hostnamevi /etc/sysconfig/networkHOSTNAME=hadoop001(-xxx)hostname hadoop001(-xxx)vi /etc/hosts116.207.129.116 hadoop001reboot1.Download and Check MD5 cd /usr/local_安装cdh不安装mysql

Android安装GDB/GDB server_安卓13安装gdbserver-程序员宅基地

文章浏览阅读2.7k次。在没有安卓系统源码,还想调试系统代码查看崩溃信息的时候也可以用gdb或者gdbserver来调试,但是手机里没有装gdb或gdbserver。记录一下手动安装踩的坑: 首先,需要下载编译好的gdbserver。官方渠道可以从ndk-toolchain中里找,解压后在/prebuild文件夹下找对应处理器架构的版本。 然后通过adb push到手机上。貌似即使手机root之后,adb push也只_安卓13安装gdbserver

推荐文章

热门文章

相关标签