vue 封装组件时,优雅的将子组件属性和方法对父组件暴露

对 el-input 进行封装,封装为 my-input
<template>
  
  
  <el-input
    v-model="value"
    v-bind="$attrs"
    v-on="$listeners">
    
    <template v-for="(index, name) in $slots" v-slot:[name]>
      <slot :name="name" />
    template>
    
    <template v-for="(index, name) in $scopedSlots" v-slot:[name]="data">
      <slot :name="name" v-bind="data">slot>
    template>
  el-input>
template>

<script>
  export default {
    name: 'MyInput',
    inheritAttrs: false,  // 避免将未声明的 props 在 DOM 节点上注册
    data() {
      return {
        value:''
      }
    },
    props: {
      type: {
        default: 'a',
        // 使用 validator 抛出参数异常,如果返回为 false 则异常
        validator: prop => ['a','b','c'].includes(prop)
      }
    },
    created() {

    },
    methods: {
      myFunc() {
        console.log('myFunc')
      }
    }
  }
script>

<style scoped>

style>

在实际场景中使用 my-input

<template>
  <my-input $ref="myInput" clearable @clear="handleClear"/>
template>

<script>
  import MyInput from './my-input'
  export default {
    name: 'test',
    components: { MyInput },
    data() {
      return {

      }
    },
    created() {

    },
    mounted() {
      // 使用 $ref 调用内部方法
      this.$refs.myInput.myFunc()
    },
    methods: {
      handleClear() {
        console.log('clear')
      }
    }
  }
script>

<style scoped>

style>

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