search
HomeWeb Front-endJS TutorialHow to implement a side-sliding menu component in Vue

This article introduces the implementation of a simple DrawerLayout (similar to Android's DrawerLayout) layout component. Let's learn the implementation code based on the Vue.js side sliding menu component through this article.

This article introduces a simple DrawerLayout ( Implementation of layout components similar to Android's DrawerLayout, based on Vue.js. The introduced content has been made into vue-drawer-layout component.

Preface

If you are interested, please scan this QR code with your mobile phone first, or click on my

and then click Open the drawer or drag the avatar in the upper left corner of the page to the right or left, and you can see the effect of the following gif. Open your own mobile QQ, doesn't it look like it? :)

Google officially calls this layout DrawerLayout (drawer navigation bar). So how do we achieve it? Let’s start the main movie!

HTML structure

The page structure is very simple, with a drawer and a main container. The content can be customized externally using slots.

<p class="drawer-layout">
  <!--抽屉-->
  <p class="drawer-wrap">
    <slot name="drawer"></slot>
  </p>
  <!--主容器-->
  <p class="content-wrap">
    <!--遮罩-->
    <p class="drawer-mask"></p>
    <slot name="content"></slot>
  </p>
</p>

The drawer is initially hidden outside the left screen, so set left:-100% to hide the entire drawer outside.

Use Touch

First, determine whether the browser supports touchEvent

let isTouch = &#39;ontouchstart&#39; in window;
  let mouseEvents = isTouch ?
    {
      down: &#39;touchstart&#39;,
      move: &#39;touchmove&#39;,
      up: &#39;touchend&#39;,
      over: &#39;touchstart&#39;,
      out: &#39;touchend&#39;
    } :
    {
      down: &#39;mousedown&#39;,
      move: &#39;mousemove&#39;,
      up: &#39;mouseup&#39;,
      over: &#39;mouseover&#39;,
      out: &#39;mouseout&#39;
    };

Bind the touchdown event

document.addEventListener(mouseEvents.down, initDrag, false);

First define some Variable, the x-coordinate of the finger pressed is marked as startX, the x-coordinate of the finger during sliding is marked as nowX, and the x-coordinate offset of the drawer is marked as startPos

let startX, nowX, startPos;

When touchstart is triggered, the starting position is recorded and bound Determine touchmove, note: If it is a mouseEvent, get the current x coordinate through e.clientX. If it is a touchEvent, get the x coordinate through e.changedTouches[0].clientX

const initDrag = function (e) {
  startX = e.clientX || e.changedTouches[0].clientX; //记录手指按下的位置
  startPos = this.pos; //记录drawer的上次位置
  document.addEventListener(mouseEvents.move, drag, false);
  document.addEventListener(mouseEvents.up, removeDrag, false);
}.bind(this);
const drag = function (e) {
  nowX = e.clientX || e.changedTouches[0].clientX; //滑动中手指的位置x坐标
  let pos = startPos + nowX - startX; 
  pos = Math.min(width, pos); //不能超过滑动最大值
  pos = Math.max(0, pos); //不能小于0
  this.pos = pos; //设置滚动距离为拖动的距离
}.bind(this);

Then, the finger slides The distance is nowX - startX, and the current drawer position is startPos nowX - startX, so that the drawer has followed the finger to move to the right, and will not exceed the maximum drag value we set.

Distinguish between vertical sliding and horizontal sliding

Next you will find a problem, when your finger scrolls the main content vertically, slide your finger to the right It will also drag out the drawer. At this time, you should do one thing: distinguish between vertical sliding and horizontal sliding.

Of course, there are many ways. Here is a method that uses trigonometric functions to determine.

Assume that each arrow in the above picture is the direction of the finger sliding. The green arrow means that the drawer can be dragged out, and the red arrow means that it cannot be dragged out (note that the red arrow also has the offset of the x coordinate). displacement). That is, when the drawer cannot be dragged out, default events should be triggered, such as vertical scrolling, etc.

When the finger presses to trigger touchstart, the initial position P 0 is recorded; when the finger is slid, the first touchmove is triggered, the position P 1 is recorded, and we record the vector from P 0 to P 1 as S (Forgive me for being a soul painter)

It is easy to see at this time that when ∠θ is greater than a certain value, such as 30 degrees, it may be a vertical scrolling operation Instead of dragging the drawer. Therefore, the judgment condition can be obtained based on y/x>tan30°

:

if (isVerticle === undefined) isVerticle = Math.abs(nowY - startY) / Math.abs(nowX - startX) > (Math.sqrt(3) / 3);

When isVerticle is true, dragging of the drawer will not be performed

Let the Drawer move

We use the transition attribute of css3 to make the drawer have a transition animation effect. Here we write a moving class

.moving
  transition transform .3s ease

Don’t forget to add class binding. There is no need for transition animation when dragging (required Follow your finger), and the transition animation is only needed when you release your finger.

<p class="drawer-wrap" :class="{&#39;moving&#39;:moving,&#39;will-change&#39;:willChange}"
   :style="{width:`${width}px`,left:`-${width)}px`,transform:`translate3d(${pos}px,0,0)`}">
  <slot name="drawer"></slot>
</p>

So you need to do these steps when binding the touchend event method

const removeDrag = function (e) {
  if (isVerticle !== undefined) {
    if (!isVerticle) {//当判定为抽屉拖动才进入
      let pos = this.pos;
      this.visible = pos > width * 3 / 5 //当前位置如果大于总宽度的3/5就判定为全部展开抽屉,否则将抽屉弹回隐藏
      if (this.pos > 0 && this.pos < width) this.moving = true;//如果位置已经处于最小值或最大值处,不需要有动画效果了
    }
    this.pos = this.visible ? width : 0;
  }
  if (!this.moving) {
    this.willChange = false; //留个悬念
  }
  isVerticle = undefined;
  //取消touchmove和touchend事件绑定
  document.removeEventListener(mouseEvents.move, drag, false);
  document.removeEventListener(mouseEvents.up, removeDrag, false);
}.bind(this);

You may find this.willChange = false in the code above. What does it do? Below we ask the will-change method of css

.will-change
will-change transform

The CSS attribute will-change provides web developers with a way to tell the browser that How the elements will change, so that the browser can make corresponding optimization preparations in advance before the element attributes actually change. This kind of optimization can prepare part of the complex calculation work in advance, making the page response faster and more sensitive.

In fact, we can inform the browser drawer in touchstart that the displacement may occur

const initDrag = function (e) {
  //...
  this.willChange = true;
}.bind(this);

Of course, don’t forget to remove the transition and will-change after the transitionend event and let the browser rest for a while ~

What else can be optimized?

The main functions mentioned above have basically been implemented, but is there anything else that can be optimized?

Huh? What the hell is passive

?

网站使用被动事件侦听器以提升滚动性能,在您的触摸和滚轮事件侦听器上设置 passive 选项可提升滚动性能具体看这里

原来这是现代浏览器的一个新特性,我们需要以新的方式来绑定我们的touch事件,当然首先先检测一下是否支持 passive

const supportsPassive = (() => {
  let supportsPassive = false;
  try {
    const opts = Object.defineProperty({}, &#39;passive&#39;, {
      get: function () {
        supportsPassive = true;
      }
    });
    window.addEventListener("test", null, opts);
  } catch (e) {
  }
  return supportsPassive;
})();

于是我们的绑定事件代码变成这样

document.addEventListener(mouseEvents.move, drag, supportsPassive ? {passive: true} : false);

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

Bootstrap栅格系统(详细教程)

在jQuery中如何实现点击DIV触发点击CheckBox

在React Native中使用prop-types如何实现属性确认

在jQuery中如何实现弹窗下底部页面禁止滑动效果

$refs访问Vue中的DOM(详细教程)

The above is the detailed content of How to implement a side-sliding menu component in Vue. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

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

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)