002_组件的二次封装

一、介绍

针对element-ui的el-input组件进行封装,需要添加element-ui的依赖

二、FirstCustomWrapInput组件

<template>
  <div>
    <el-input
      v-model="value"
      @input="$emit('input', value)"
      @blur="$emit('blur1')"
      @focus="$emit('focus1')"
    ></el-input>
  </div>
</template>


<script>
export default {
  name: "FirstCustomWrapInput",
  //方式一:需要model、props
  model: {
    prop: "initValue",
    event: "input",
  },
  props: ["initValue"],
  data() {
    return {
      value: this.initValue,
    };
  },
  watch:{
    // 监视props种initValue的变化,从而更新当前value,从而实现双向绑定。因为要避免直接修改props属性
    initValue(newValue){
      this.value = newValue
    }
  }
};
</script>

<style scoped>
.el-input {
  padding: 20px;
}

/* 这种方式可以访问到添加hash属性之后的下面样式 */
.el-input >>> .el-input__inner {
  background: #bfa;
  border-top: none;
  border-left: none;
  border-right: none;
}
</style>

三、SecondCustomWrapInput组件

<template>
  <div>
    <!-- 这种使用方式会要求,父组件传递的$listeners里面的属性名称
    是所封装组件能触发的。否则无效 -->
    <el-input v-bind="$attrs" v-on="$listeners"></el-input>
  </div>
</template>


<script>
export default {
  name: "SecondCustomWrapInput",
};
</script>

<style scoped>
.el-input {
  padding: 20px;
}

.el-input >>> .el-input__inner {
  background: #bfa;
  border-top: none;
  border-left: none;
  border-right: none;
}
</style>

四、App组件

<template>
  <div id="app">
    <h3>方式一</h3>
    <first-custom-wrap-input
      v-model="value"
      @blur1="handleBlur"
      @focus1="handleFocus"
    ></first-custom-wrap-input>
    <hr/>
    
    <h3>方式二</h3>
    <second-custom-wrap-input
      v-model="value"
      @blur="handleBlur"
      @focus="handleFocus"
    ></second-custom-wrap-input>
    value当前值:{{ value }}
    <hr/>
    
    <h3>element-ui组件</h3>
    <el-input v-model="value"/>
    <button @click="value='国货之光'">点我</button>
  </div>
</template>

<script>
import FirstCustomWrapInput from "./components/FirstCustomWrapInput.vue";
import SecondCustomWrapInput from "./components/SecondCustomWrapInput.vue";

export default {
  name: "App",
  components: { FirstCustomWrapInput,SecondCustomWrapInput },
  data() {
    return {
      value: "333",
    };
  },
  methods: {
    handleBlur() {
      console.log("blur");
    },
    handleFocus() {
      console.log("focus");
    },
  },
};
</script>

<style scoped>
#app {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
  padding: 100px;
}
</style>

四、效果图

002_组件的二次封装_第1张图片

你可能感兴趣的:(#,VUE,vue.js,javascript,前端)