Home Web Front-end JS Tutorial Vue implements the component that returns the top backToTop

Vue implements the component that returns the top backToTop

Jun 29, 2018 pm 03:40 PM
vue Back to top

This article mainly introduces the implementation of a backToTop component in Vue, which can achieve the return to the top effect and has certain reference value. If you are interested, you can learn about

I have been learning VUE recently. I am studying how to use VUE to implement the encapsulation of a component. I will leave a note today

Preface

Back to topThis function can be implemented using jq. It is so easy. Implementation, an animate combined with scrollTo can be done.

Today we will try vue to encapsulate a native js implementation. Return to the top;
It’s quite difficult to write. With the help of github, I looked at other people’s gist and encapsulated it a little. ;

Of course it’s not the kind of direct adjustment using scrollTo. How can it be justified without a transition effect!! It’s still done.

Without further ado, let’s look at the renderings...

Rendering

Implementation ideas

  1. The transition uses requestAnimationFrame, which The product only supports IE10, so it must be compatible

  2. The scroll view is window.pageYOffset, and this product supports IE9;

  3. In order to make it controllable Better, use iconfont for the icon, look at the code in detail

What can you learn?

  1. Learn some pages Calculation related stuff

  2. Some knowledge of animation API

  3. Vue encapsulation component related knowledge and the application of life cycle and event monitoring and destruction related knowledge

Implementation function

  1. The view displays the return to top button and icon at 350 by default

  2. Prompt text and color, customization of the top, bottom, left and right of the icon, the fields have limited formats and default values

  3. Icon color, shape, size customization Definition, fields have limited formats and default values

  4. Customization of transition effects, usage: scrollIt(0, 1500, 'easeInOutCubic', callback);

    1. Return to the point of the view, that is, where to scroll

    2. Transition time (ms level)

    3. A bunch of transition effects and string formats are actually rolling calculation functions..

    4. Of course, the default parameters are indispensable, except for callback

  5. The compatibility is IE9, I specially opened the virtual machine to try it

Code

scrollIt.js – Transitional scrolling implementation

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

export function scrollIt(

 destination = 0,

 duration = 200,

 easing = "linear",

 callback

) {

 // define timing functions -- 过渡动效

 let easings = {

  // no easing, no acceleration

  linear(t) {

   return t;

  },

  // accelerating from zero velocity

  easeInQuad(t) {

   return t * t;

  },

  // decelerating to zero velocity

  easeOutQuad(t) {

   return t * (2 - t);

  },

  // acceleration until halfway, then deceleration

  easeInOutQuad(t) {

   return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t;

  },

  // accelerating from zero velocity

  easeInCubic(t) {

   return t * t * t;

  },

  // decelerating to zero velocity

  easeOutCubic(t) {

   return --t * t * t + 1;

  },

  // acceleration until halfway, then deceleration

  easeInOutCubic(t) {

   return t < 0.5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1;

  },

  // accelerating from zero velocity

  easeInQuart(t) {

   return t * t * t * t;

  },

  // decelerating to zero velocity

  easeOutQuart(t) {

   return 1 - --t * t * t * t;

  },

  // acceleration until halfway, then deceleration

  easeInOutQuart(t) {

   return t < 0.5 ? 8 * t * t * t * t : 1 - 8 * --t * t * t * t;

  },

  // accelerating from zero velocity

  easeInQuint(t) {

   return t * t * t * t * t;

  },

  // decelerating to zero velocity

  easeOutQuint(t) {

   return 1 + --t * t * t * t * t;

  },

  // acceleration until halfway, then deceleration

  easeInOutQuint(t) {

   return t < 0.5 ? 16 * t * t * t * t * t : 1 + 16 * --t * t * t * t * t;

  }

 };

 // requestAnimationFrame()的兼容性封装:先判断是否原生支持各种带前缀的

 //不行的话就采用延时的方案

 (function() {

  var lastTime = 0;

  var vendors = ["ms", "moz", "webkit", "o"];

  for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {

   window.requestAnimationFrame =

    window[vendors[x] + "RequestAnimationFrame"];

   window.cancelAnimationFrame =

    window[vendors[x] + "CancelAnimationFrame"] ||

    window[vendors[x] + "CancelRequestAnimationFrame"];

  }

 

  if (!window.requestAnimationFrame)

   window.requestAnimationFrame = function(callback, element) {

    var currTime = new Date().getTime();

    var timeToCall = Math.max(0, 16 - (currTime - lastTime));

    var id = window.setTimeout(function() {

     callback(currTime + timeToCall);

    }, timeToCall);

    lastTime = currTime + timeToCall;

    return id;

   };

 

  if (!window.cancelAnimationFrame)

   window.cancelAnimationFrame = function(id) {

    clearTimeout(id);

   };

 })();

 

 function checkElement() {

  // chrome,safari及一些浏览器对于documentElemnt的计算标准化,reset的作用

  document.documentElement.scrollTop += 1;

  let elm =

   document.documentElement.scrollTop !== 0

    ? document.documentElement

    : document.body;

  document.documentElement.scrollTop -= 1;

  return elm;

 }

 

 let element = checkElement();

 let start = element.scrollTop; // 当前滚动距离

 let startTime = Date.now(); // 当前时间

 

 function scroll() { // 滚动的实现

  let now = Date.now();

  let time = Math.min(1, (now - startTime) / duration);

  let timeFunction = easings[easing](time);

  element.scrollTop = timeFunction * (destination - start) + start;

 

  if (element.scrollTop === destination) {

   callback; // 此次执行回调函数

   return;

  }

  window.requestAnimationFrame(scroll);

 }

 scroll();

}

Copy after login

backToTop.vue

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

<template>

 <p class="back-to-top" @click="backToTop" v-show="showReturnToTop" @mouseenter="show" @mouseleave="hide">

  <i :class="[bttOption.iClass]" :style="{color:bttOption.iColor,&#39;font-size&#39;:bttOption.iFontsize}"></i>

  <span class="tips" :class="[bttOption.iPos]" :style="{color:bttOption.textColor}" v-show="showTooltips">{{bttOption.text}}</span>

 </p>

</template>

 

<script>

 import { scrollIt } from &#39;./scrollIt&#39;; // 引入动画过渡的实现

 export default {

  name: &#39;back-to-top&#39;,

  props: {

   text: { // 文本提示

    type: String,

    default: &#39;返回顶部&#39;

   },

   textColor: { // 文本颜色

    type: String,

    default: &#39;#f00&#39;

   },

   iPos: { // 文本位置

    type: String,

    default: &#39;right&#39;

   },

   iClass: { // 图标形状

    type: String,

    default: &#39;fzicon fz-ad-fanhuidingbu1&#39;

   },

   iColor: { // 图标颜色

    type: String,

    default: &#39;#f00&#39;

   },

   iFontsize: { // 图标大小

    type: String,

    default: &#39;32px&#39;

   },

   pageY: { // 默认在哪个视图显示返回按钮

    type: Number,

    default: 400

   },

   transitionName: { // 过渡动画名称

    type: String,

    default: &#39;linear&#39;

   }

  },

  data: function () {

   return {

    showTooltips: false,

    showReturnToTop: false

   }

  },

  computed: {

   bttOption () {

    return {

     text: this.text,

     textColor: this.textColor,

     iPos: this.iPos,

     iClass: this.iClass,

     iColor: this.iColor,

     iFontsize: this.iFontsize

    }

   }

  },

  methods: {

   show () { // 显示隐藏提示文字

    return this.showTooltips = true;

   },

   hide () {

    return this.showTooltips = false;

   },

   currentPageYOffset () {

    // 判断滚动区域大于多少的时候显示返回顶部的按钮

    window.pageYOffset > this.pageY ? this.showReturnToTop = true : this.showReturnToTop = false;

 

   },

   backToTop () {

    scrollIt(0, 1500, this.transitionName, this.currentPageYOffset);

   }

  },

  created () {

   window.addEventListener(&#39;scroll&#39;, this.currentPageYOffset);

  },

  beforeDestroy () {

   window.removeEventListener(&#39;scroll&#39;, this.currentPageYOffset)

  }

 }

</script>

 

<style scoped lang="scss">

 .back-to-top {

  position: fixed;

  bottom: 5%;

  right: 100px;

  z-index: 9999;

  cursor: pointer;

  width: auto;

  i {

   font-size: 32px;

   display: inline-block;

   position: relative;

   text-align: center;

   padding: 5px;

   background-color: rgba(234, 231, 231, 0.52);

   border-radius: 5px;

   transition: all 0.3s linear;

   &:hover {

    border-radius: 50%;

    background: #222;

    color: #fff !important;

   }

  }

  .tips {

   display: inline-block;

   position: absolute;

   word-break: normal;

   white-space: nowrap;

   width: auto;

   font-size: 12px;

   color: #fff;

   z-index: -1;

  }

  .left {

   right: 0;

   top: 50%;

   margin-right: 50px;

   transform: translateY(-50%);

  }

  .right {

   left: 0;

   top: 50%;

   margin-left: 50px;

   transform: translateY(-50%);

  }

  .bottom {

   bottom: 0;

   margin-top: 50px;

  }

  .top {

   top: 0;

   margin-bottom: 50px;

  }

 }

</style>

Copy after login

Summary

From whim to tossing, in order to balance compatibility and expansion Sex, it seemed like a few hours.

But it was realized. If you move to other languages, like ng4, it only takes about ten minutes,

The ideas will be Well, the implementation is more about writing. As for performance optimization, you can think about it while writing, or you can optimize it when you have time after implementation.

The above is the entire content of this article. I hope it will be helpful to everyone's study. , please pay attention to the PHP Chinese website for more related content!

Related recommendations:

About the use of the VUE-region selector (V-Distpicker) component

About vue Introduction to the construction, packaging and release process of the project

The above is the detailed content of Vue implements the component that returns the top backToTop. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1253
29
C# Tutorial
1228
24
How to use bootstrap in vue How to use bootstrap in vue Apr 07, 2025 pm 11:33 PM

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

How to add functions to buttons for vue How to add functions to buttons for vue Apr 08, 2025 am 08:51 AM

You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

How to use watch in vue How to use watch in vue Apr 07, 2025 pm 11:36 PM

The watch option in Vue.js allows developers to listen for changes in specific data. When the data changes, watch triggers a callback function to perform update views or other tasks. Its configuration options include immediate, which specifies whether to execute a callback immediately, and deep, which specifies whether to recursively listen to changes to objects or arrays.

What does vue multi-page development mean? What does vue multi-page development mean? Apr 07, 2025 pm 11:57 PM

Vue multi-page development is a way to build applications using the Vue.js framework, where the application is divided into separate pages: Code Maintenance: Splitting the application into multiple pages can make the code easier to manage and maintain. Modularity: Each page can be used as a separate module for easy reuse and replacement. Simple routing: Navigation between pages can be managed through simple routing configuration. SEO Optimization: Each page has its own URL, which helps SEO.

How to return to previous page by vue How to return to previous page by vue Apr 07, 2025 pm 11:30 PM

Vue.js has four methods to return to the previous page: $router.go(-1)$router.back() uses &lt;router-link to=&quot;/&quot; component window.history.back(), and the method selection depends on the scene.

How to reference js file with vue.js How to reference js file with vue.js Apr 07, 2025 pm 11:27 PM

There are three ways to refer to JS files in Vue.js: directly specify the path using the &lt;script&gt; tag;; dynamic import using the mounted() lifecycle hook; and importing through the Vuex state management library.

How to use vue traversal How to use vue traversal Apr 07, 2025 pm 11:48 PM

There are three common methods for Vue.js to traverse arrays and objects: the v-for directive is used to traverse each element and render templates; the v-bind directive can be used with v-for to dynamically set attribute values ​​for each element; and the .map method can convert array elements into new arrays.

React vs. Vue: Which Framework Does Netflix Use? React vs. Vue: Which Framework Does Netflix Use? Apr 14, 2025 am 12:19 AM

Netflixusesacustomframeworkcalled"Gibbon"builtonReact,notReactorVuedirectly.1)TeamExperience:Choosebasedonfamiliarity.2)ProjectComplexity:Vueforsimplerprojects,Reactforcomplexones.3)CustomizationNeeds:Reactoffersmoreflexibility.4)Ecosystema

See all articles