preface

The steps for encapsulating components listed in this article take the Element UI back to the top component as an example, but are not limited to it (at least as a reference). The demo presented has also been modified a bit.

Encapsulate steps

The following answers are only personal views on vUE component packaging, not all correct, if there is any inappropriate, please understand.

1. Determine whether the component to be encapsulated is decorative or functional.

The question is easy to understand, in plain English, what the component you are encapsulating does. So what component is the back to the top button for this article? The obvious answer is that it’s a functional component, because it’s designed to let the user click to move the scrollbar from the bottom of the page back to the top.

2. Scenario analysis

What is it that you’re encapsulating that needs to be used for? Take the back to the top button for example. The main scenario for using it is a long page that requires scrolling down, and when you get back to the top, you can do it in one step (scrolling up without using your fingers).

3. Status analysis

This step is usually used to encapsulate decorative components. For example, a button component, which generally has the following states:

  • The default state
  • The successful state
  • State information
  • Warning state
  • Dangerous state

For the button-like component back at the top, we just need a default state (that is, initialization). For example, what is the distance from the bottom or right margin of the page, what is the scroll height of the display button, etc.

4. Morphological analysis

This mainly refers to how the components you encapsulate appear (i.e., CSS styles). In general, button components have a selection of shapes, styles and animation effects, such as:

  • circular
  • A square
  • Fade in and out transition animation

For the back to the top button component, we are going to let the developer design it by slot, so that the component style is not fixed to a limited number of components, but very colorful.

5. Size

Typically, button-shaped components come in several different sizes to choose from.

  • Small, small
  • Medium, medium
  • Large –

Since it is intended to be customizable, there is no need to design an optional size.

6. Event listener function

When encapsulating a VUE component, it is common to set up event listeners to perform certain actions.

7. Expose external attributes and events

Through the above series of analyses, we may expose the following properties and event listeners.

attribute

parameter instructions type The default value
target The object that triggers scrolling string
visibility-height The rolling height reaches this parameter value number 200
right Controls its display position, from the right margin of the page number 40
bottom Controls its display position, distance from the bottom of the page number 40
transition-name Transition animation string el-fade-in

The event

parameter instructions The callback parameter
click The event triggered by clicking a button Click on the event

Code implementation

Notice that the entire component is unchanged except for adding a transition-name transition animation property to it.

HTML structure layout

<template>
  <transition :name="transitionName">
    <div v-if="visible"
      :style="{ 'right': styleRight, 'bottom': styleBottom }"
      class="el-backtop"
      @click.stop="handleClick"
    >
      <! -- The default style in the slot, which can be changed according to personal preference, needs to be passed when using the component -->
      <slot>
        <el-icon name="caret-top" />
      </slot>
    </div>
  </transition>
</template>
Copy the code

Js code

Throttle was introduced in the code to prevent the user from repeatedly clicking the button to trigger the scroll function. You can install throttle-debounce –save in your project by using NPM install throttle-debounce –save, or as I wrote in the code: as a file, if you download it first. If you are interested in throttling and shaking prevention, you may wish to read my related article.

<script>
// throttling to ensure that only one event handler is called in a certain period of time. Prevent users from clicking repeatedly.
import throttle from './js/throttle'

// Set the scrolling animation effect
const cubic = value= > Math.pow(value, 3)
const easeInOutCubic = value= > value < 0.5
  ? cubic(value * 2) / 2
  : 1 - cubic((1 - value) * 2) / 2

export default {
  name: 'ElBacktop'.props: {
    // Roll height
    visibilityHeight: {
      type: Number.default: 200
    },
    // The object that triggers the scroll
    target: [String].// Right margin of the page
    right: {
      type: Number.default: 40
    },
    // Distance at the bottom of the page
    bottom: {
      type: Number.default: 40
    },
    // Transition animation
    transitionName: {
      type: String.default: 'el-fade-in'}},data() {
    return {
      el: null.// The object that triggers the scroll
      container: null.visible: false // Control component display}},computed: {
    // Use the calculated property to listen for bottom and right values
    styleBottom() {
      return `The ${this.bottom}px`
    },
    styleRight() {
      return `The ${this.right}px`}},mounted() {
    / / initialization
    this.init()
    // Generate the throttling function and return it
    this.throttledScrollHandler = throttle(300.this.onScroll)
    // Listen for scroll events
    this.container.addEventListener('scroll'.this.throttledScrollHandler)
  },
  // Destroy the hook
  beforeDestroy() {
    // Remove scroll event
    this.container.removeEventListener('scroll'.this.throttledScrollHandler)
  },

  methods: {
    // Initialization, mainly to get the scrolling object
    init() {
      this.container = document
      this.el = document.documentElement
      if (this.target) {
        this.el = document.querySelector(this.target)
        if (!this.el) {
          throw new Error(`target is not existed: The ${this.target}`)}this.container = this.el
      }
    },
    // Listen for scroll values used to show and hide back to the top button component
    onScroll() {
      const scrollTop = this.el.scrollTop
      this.visible = scrollTop >= this.visibilityHeight
    },
    // Click the event
    handleClick(e) {
      this.scrollToTop()
      this.$emit('click', e) // Trigger the parent listener event function click
    },
    // The scroll function
    scrollToTop() {
      const el = this.el // Scroll objects
      const beginTime = Date.now() // Start scrolling time
      const beginValue = el.scrollTop // Roll distance
      // Perform the animation
      const rAF = window.requestAnimationFrame || (func= > setTimeout(func, 16))
      // Update the animation callback function
      const frameFunc = () = > {
        // Control the animation progress
        const progress = (Date.now() - beginTime) / 500
        // If progress is greater than 1, the scroll animation is complete and the scroll bar returns to the top
        if (progress < 1) {
          el.scrollTop = beginValue * (1 - easeInOutCubic(progress))
          rAF(frameFunc)
        } else {
          el.scrollTop = 0}}// call back to continue the scrolling animation
      rAF(frameFunc)
    }
  }
}
</script>
Copy the code

use

The back to the top component of elementui does not have the transition-name animation property, so I changed it a little bit and added it here. .

/ / way
<BackTop :bottom="100" transition-name="el-fade-in-linear">
    <div
    style="{ height: 100%; width: 100%; background-color: #f2f5f6; Box-shadow: 0 0 6px rgba(0,0,0,.12); text-align: center; line-height: 40px; color: #1989fa; }"
    >
        UP
    </div>
</BackTop>

2 / / way
<BackTop :bottom="100" transition-name="el-fade-in-linear"></BackTop>
Copy the code

The last

There is nothing profound to discuss in this article, but IT is mainly to share with the students some of my personal feelings of encapsulating VUE components. If there is anything wrong, please excuse me.