vue3封装一个下拉刷新组件

 组件核心代码:pullrefresh.vue

<template>
    <div 
        :class="{'animate':isTransition}"
        :style="{transform:`translateY(${distance}px)`}"
        @touchstart="handlerstart"
        @touchmove="handlermove"
        @touchend="handlerend"
    >
        <div class="refresh_tip" v-if="distance>0">释放即可刷新...</div>
        <div class="refresh_tip" v-if="modelValue">加载中...</div>
       <slot></slot>
    </div>
</template>
<script  setup>
import { ref } from "vue";
const distance = ref(0);
const startY = ref(0);
const isTransition = ref(false);
// vue  input :value
// vue3 update:modelValue  modelValue
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
});

const emits = defineEmits(["update:modelValue", "refreshEnd"]);

const handlerstart = e => {
  console.log("e", e);
  startY.value = e.touches[0].clientY;
};
const handlermove = e => {
  distance.value = e.touches[0].clientY - startY.value;
  if (distance.value > 120) {
    distance.value = 120;
  }
};
const handlerend = e => {
  distance.value = 0;
  startY.value = 0;
  isTransition.value = true;
  emits("update:modelValue", true);
  emits("refreshEnd");
};
</script>
<style scoped>
.refresh_tip {
  text-align: center;
  padding: 12px 0;
  color: #ccc;
}
</style>

注册成全局组件

import { createApp } from 'vue'
import { cons } from "./utils/index"
import './style.css'
import App from './App.vue'

import Pullfresh from "./components/pullRefresh.vue"
const app = createApp(App)
app.component("pullfresh", Pullfresh)
app.use(ElementPlus)
app.config.globalProperties.cons = cons
app.mount('#app')

组件使用:

<script setup>
import { ref } from "vue";

const arr = [
  { id: "001", name: "标题一" },
  { id: "002", name: "标题二" },
  { id: "003", name: "标题三" }
];
const loading = ref(false);
const callback = () => {
  loading.value = false;
  // setTimeout(() => {
  //   console.log("end");
  //   loading.value = false;
  // }, 2000);
};
</script>

<template>

<pullfresh v-model="loading" @refreshEnd="callback">
  <div v-for="item of arr" :key="item.id">{
   
   {item.name}}</div>
</pullfresh>
</template>

<style scoped>
.item {
  padding: 10px 0;
  border-bottom: 1px solid #ccc;
}

</style>

猜你喜欢

转载自blog.csdn.net/baidu_41601048/article/details/132136530
今日推荐