组件功能

过渡效果
自定义提示内容

Tip component

<template>
  <transition name="fade">
    <div class="tip" v-if="isOpen">
      <p class="tip-info">{{ tip }}</p>
    </div>
  </transition>
</template>
<script>
export default {
  data() {
    return {
      tip: '',
      isOpen: false
    }
  },

  methods: {
    openTip(tip) {
      this.tip = tip
      this.isOpen = true
      let timer = setTimeout(() => {
        this.isOpen = false
        clearTimeout(timer)
      }, 2000)
    }
  }
}

</script>
<style lang="postcss">
.tip {
  display: flex;
  justify-content: center;
}

.tip-info {
  position: fixed;
  z-index: 9999;
  background-color: rgba(0, 0, 0, 0.7);
  top: 100px;
  padding: 10px 15px;
  border-radius: 4px;
  color: #fff;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s;
}

.fade-enter,
.fade-leave-active {
  opacity: 0;
}

</style>

使用方法

挂载到全局组件:

import Vue from 'vue'
import Tip from '../components/Tip.vue'

const components = { Tip }

Object.keys(components).forEach(key => {
  Vue.component(key, components[key])
})

在页面中引入组件:

<template>
  <div class="login">
    <button class="login-button" @click="login">登 录</button>
    <Tip ref="tip"></Tip>
  </div>
</template>
<script>
export default {
  methods: {
    login () {
      this.$refs.tip.openTip('用户名或密码不正确')
    }
  }
}
</script>

VueBlog的默认tip就是这么实现的,主要是通过refs实现调用子组件的方法,复杂一些的可以封装成插件。