陈广安个人网站
会写代码的咸鱼
陈广安个人网站阿里云盘资源
陈广安个人网站网盘资源搜索
“ 梦想还是要有的,万一实现了呢!”
— 马云

vue3.2,二次封装elementPlus使用了v-model的组件

创建时间:2022-05-07

定义组件sub.vue

<template>
  <el-drawer v-model="pData.display" direction="rtl">
    <template #title>
      <div>搜全站</div>
    </template>
    <template #default>
      <div>
        <el-input v-model="keyword" placeholder="请输入需要搜索的关键词">
          <template #append>
            <el-button :icon="Search" />
          </template>
        </el-input>
      </div>
      <div>
        {{keyword}}
      </div>
    </template>
  </el-drawer>
</template>

<script setup>
  import { Search } from '@element-plus/icons-vue'
  import { defineEmits, defineProps, watch, reactive, ref } from "vue"

  const emit = defineEmits(['update:show'])

  //获取父页面数据
  const props = defineProps({
    show: {
      type: Boolean,
      default: false
    },
    keyword: {
      type: String,
      default: ''
    }
  })

  //当前页面数据
  const pData = reactive({
    display: false,
    keyword: '',
  })

  //深度监听父元素组件
  watch(props, (newVal, oldVal) => {
    pData.display = newVal.show;
    pData.keyword = newVal.keyword;
  }, { immediate: true })

  //监听页面中数据,赋值给父组件,达到数据同步
  watch(pData, (newVal, oldVal) => {
    emit('update:show', newVal.display)
  }, { immediate: true })

</script>


调用组件

<template>
  <a-sub v-model:show="show" keyword="666"></a-sub>
</template>

<script setup>
  import aSub from "@/components/sub.vue";
  import { ref } from "vue";
  const show = ref(false);
</script>