vue二次封装成熟的组件

在开发过程中,我们经常会使用各种ui组件,有的时候需要二次封装,或者修改样式,以方便重复使用

以element举例:

<template>
    <el-input v-model="_value" />
</template>

<script>
export default {
    props: {
        value: {
            type: String,
            default: ''
        }
    },
    computed: {
        _value: {
            get() {
                return this.value;
            },
            set(val) {
                this.$emit('input', val);
            }
        }
    }
// 其他额外的方法或操作
}
</script>

<style>
</style>

另外一种方式,则是通过render方法,将外部所有的参数原样传递过去

<script>
export default {
  name: `BaseInput`,
  functional: true,
  render(createElement, context) {
    return createElement(
      `el-input`,
      {
        ...context.data,
        props: {
          ...context.props
        },
        class: (context.data.staticClass || "") + " base_input",
        style: {
          width: context.props.width,
          ...context.data.staticStyle
        }
      },
      [
        context.slots().default //  also pass default slot to child
      ]
    );
  }
};
</script>

<style scoped>
.base_input >>> .el-input__inner {
  line-height: 39px;
  border: none;
  border-bottom: 1px solid rgba(68, 84, 105, 0.2);
  border-radius: 0;
  font-size: 16px;
  font-family: "Poppins";
  font-weight: 400;
  padding: 0;
  color: rgba(68, 84, 105, 1);
}
.base_input >>> .el-input__inner:focus {
  border-bottom: 1px solid rgba(68, 84, 105, 1);
}
</style>
[context.slots().default]部分,可以修改为context.children,就可以传递所有的slot

ps:但是遇到过一个奇怪的问题,在封装ElImage的时候,slot传递失败,最后使用context.parent.$createElement进行创建元素才成功,原因不知道

猜你喜欢

转载自www.cnblogs.com/timmer/p/12937799.html