2021-10-11 vue的第三方组件二次封装

原理

  1. v-bind="$attrs"继承所有属性和props。
  2. v-on="$listeners"继承所有的方法。
<template>
  <div style="display: contents;">
    <第三方组件名称 v-bind="$attrs" v-on="$listeners" @click="handleClick()">
      <slot name="default"> 默认slot的默认值</slot>
    </第三方组件名称>
  </div>
</template>

<script>
import 第三方组件名称 from './第三方组件文件所在目录/第三方组件名称.vue'
export default {
  name: '当前二次封装组件名称',
  components: { 
    第三方组件名称,
  },
  model: {
    prop: 'value',
    event: ['用于更新父组件绑定model的子组件emit值'],
  },
  props: {
    value: {
      type: [String, Number,],
      default: () => {
        const theDate = '由父组件v-model绑定后传入的名为value的props默认值'
        return theDate
      },
    },
  },
  data() {
    return {
      stateControl: {
        theValue: '当前组件内部value的默认值',
      },
    }
  },
  watch: {
    async value() {
      if (this.stateControl.theValue !== this.value) {
        this.stateControl.theValue = this.value
      }
    },
    'stateControl.theValue'() {
      if (this.stateControl.theValue !== this.value) {
        const params = this.stateControl.theValue
        this.$emit('用于更新父组件绑定model的子组件emit值', params)
      }
    },
  },
  mounted() {
    this.handleClick()
  },
  methods: {
    handleClick() {
      console.log('当前二次封装组件内部点击事件;')
    },
  },
}
</script>

说明

  1. 这种方式没有让第三方组件直接继承父组件的slot,即第三方组件的slot需要自己补充实现。

来源

  1. vue继承一个组件,对element-ui二次开发;
posted @ 2021-10-11 15:51  方朝端  阅读(37)  评论(0编辑  收藏  举报

我的页脚HTML代码