关于vue3:vue3封装一个带动画的关闭按钮

预览成果:

实现源码:

<template>
  <MenuBtn
      :open="openMenu"
      :size="24"
  />
</template>
<template>
  <div :class="`menu ${open?'open':''}`" :style="`width:${size}px;height:${size}px`">
    <span
        :style="`
          transition-duration:${duration}ms;
          transform:${open?`translateY(${(size-2)/2}px) rotate(-45deg)`:`translateY(${size/6}px)`};
        `"
    />
    <span
        :style="`
          transition-duration:${duration}ms;
          ${open?`opacity: 0;transform: rotate(-45deg)`:''}
        `"
    />
    <span
        :style="`
          transition-duration:${duration}ms;
          transform:${open?`translateY(${-(size-2)/2}px) rotate(45deg)`:`translateY(-${size/6}px)`};
        `"
    />
  </div>
</template>
<script setup>
// 这里用了vue3的专用写法。vue2写法,自行实现。
const {open, size, duration} = defineProps({
  open: {
    type: Boolean,
    default: false,
    required: true,
  },
  size: {
    type: Number,
    default: 24,
    required: false
  },
  duration: {
    type: Number,
    default: 300,
    required: false
  }
});
</script>
<style scoped lang="scss">
.menu {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-direction: column;

  span {
    height: 2px;
    border-radius: 2px;
    display: flex;
    width: 100%;
    background-color: #333;
  }
}
</style>

源码阐明:
带有变量的款式,都写在行内了,因为这样适宜用在任意场景下。

// nuxt3 
npx nuxi init <project-name>

// nuxt2
yarn create nuxt-app <project-name>

// vue-cli
vue create <project-name>

// vite
npm init vite-app <project-name>

其余场景:
vite能够间接在style标签中应用js变量

npm init vite-app <project-name>
<template>
  <h1>{color}</h1>
</template>

<script>
export default {
  data () {
    return {
      color: 'red'
    }
  }
}
</script>

<style vars="{ color }" scoped>
h1 {
  color: var(--color);
}
</style>

【腾讯云】轻量 2核2G4M,首年65元

阿里云限时活动-云数据库 RDS MySQL  1核2G配置 1.88/月 速抢

本文由乐趣区整理发布,转载请注明出处,谢谢。

您可能还喜欢...

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据