Table of Contents
3.wxs response event" >3.wxs response event
Home Web Front-end uni-app How does uniapp implement the free drag and drop function on the mini program page?

How does uniapp implement the free drag and drop function on the mini program page?

Sep 07, 2021 pm 07:28 PM
uniapp Applets

How does uniapp implement the free drag-and-drop function on the mini program page? The following article will introduce to you how uniapp implements free drag and drop components on mini program pages. I hope it will be helpful to you!

How does uniapp implement the free drag and drop function on the mini program page?

Let’s look at the implementation effect first:

How does uniapp implement the free drag and drop function on the mini program page?

[Related recommendations : "uniapp tutorial"]

Implementation process

According to the documentation, there are about three steps to realize the drag-and-drop function. One way:

1. Monitor the catchtouchmove event for the element that needs to be dragged, and dynamically modify the style coordinates

This method is the easiest to think of, using js to monitor the touch position and dynamically modify the element coordinates. However, drag and drop is an operation that requires very high real-time performance. You cannot set a throttling function in this operation to reduce the setData operation. Moreover, each setData operation itself is relatively performance-intensive, and it is easy to cause drag and drop lags. This Options can be eliminated first.

2.movable-area movable-view

The role of the movable-area component is to define an area in which the movable- The components of the view can be moved freely by the user, and the movable-view can easily set the zoom effect. According to the component definition, you can think of its usage scenario as dragging and scaling some elements in a local area of ​​the page. This is inconsistent with our need to freely drag and drop across the entire page.

3.wxs response event

wxs is specially used to solve scenarios with frequent interactions. It runs directly in the view layer, eliminating the need for the view layer and the logic layer. The performance loss caused by communication can be achieved to achieve smooth animation effects. For details, see: wxs response event. According to the usage scenarios of wxs, we can basically determine that the wxs solution should be used to implement the functions we want.

Code implementation

We use the uniapp framework, check the uniapp documentation, the official directly provides a free drag and drop code example, link Click here.

Just take the official code example and modify it, as follows:

<template>
    <view catchtouchmove="return">
        <view @click="play" @touchstart="hudun.touchstart" @touchmove="hudun.touchmove" @touchend="hudun.touchend">
            <canvas id="lottie-canvas" type="2d" style="width: 88px; height: 102px;"></canvas>
        </view>
    </view>
</template>

<script module="hudun">
    var startX = 0
    var startY = 0
    var lastLeft = 20
    var lastTop = 20

    function touchstart(event, ins) {
        ins.addClass(&#39;expand&#39;)
        var touch = event.touches[0] || event.changedTouches[0]
        startX = touch.pageX
        startY = touch.pageY
    }
    
    function touchmove(event, ins) {
        var touch = event.touches[0] || event.changedTouches[0]
        var pageX = touch.pageX
        var pageY = touch.pageY
        var left = pageX - startX + lastLeft
        var top = pageY - startY + lastTop
        startX = pageX
        startY = pageY
        lastLeft = left
        lastTop = top
        ins.selectComponent(&#39;.movable&#39;).setStyle({
            right: -left + &#39;px&#39;,
            bottom: -top + &#39;px&#39;
        })
    }
    
    function touchend(event, ins) {
        ins.removeClass(&#39;expand&#39;)
    }
    
    module.exports = {
        touchstart: touchstart,
        touchmove: touchmove,
        touchend: touchend
    }
</script>

<script>
    import lottie from &#39;lottie-miniprogram&#39;
    let insList = {} // 存放动画实例集合
    export default {
        props: {
            tag: String
        },
        data() {
            return {
                isPlay: true,
            }
        },
        methods: {
            init() {
                const query = uni.createSelectorQuery().in(this)
                query.select(&#39;#lottie-canvas&#39;).fields({ node: true, size: true }).exec((res) => {
                    const canvas = res[0].node
                    const context = canvas.getContext(&#39;2d&#39;)
                    const dpr = uni.getSystemInfoSync().pixelRatio
                    canvas.width = res[0].width * dpr
                    canvas.height = res[0].height * dpr
                    context.scale(dpr, dpr)
                    lottie.setup(canvas)
                    const ins = lottie.loadAnimation({
                        loop: true,
                        autoplay: true,
                        path: &#39;https://usongshu.oss-cn-beijing.aliyuncs.com/data/other/f8780255686b0bb35d25464b2eeea294.json&#39;,
                        rendererSettings: {
                            context,
                        },
                    })
                    insList[this.tag] = ins
                    setTimeout(() => {
                        this.isPlay = false
                        ins.stop()
                    }, 3000)
                })
            },
            play() {
                const ins = insList[this.tag]
                if (!this.isPlay) {
                    this.isPlay = true
                    ins.play()
                    setTimeout(() => {
                        this.isPlay = false
                        ins.stop()
                    }, 3000)
                }
            }
        },
        beforeDestroy() {
            delete insList[this.tag]
        }
    }
</script>

<style>
    .area
        position fixed
        right 20px
        bottom 20px
        width 88px
        height 102px
        z-index 99999

    .expand
        width 100vw
        height 100vh

    .movable
        position absolute
</style>
Copy after login

The above code is the complete code implemented in the opening renderings, and has been encapsulated into a separate component. What we want to drag is a canvas element, using the lottie animation library, which will play the animation when clicked. If you want to implement a simple button drag on the page, the amount of code will be much less. If the function you want to implement is similar to this, then the following points in the above code need to be explained:

1. Our requirement is to be displayed on multiple pages. After consulting the relevant information, it cannot be achieved. To place a component in only one place and then display it on every page, the component must be introduced on every page. Fortunately, uniapp supports defining global applet components, which can help us reduce the amount of code introduced. Here’s how: Define the component in main.js and use it in the

// 动画组件
import { HudunAnimation } from &#39;@/components/hudun-animation/index&#39;
Vue.component(&#39;HudunAnimation&#39;, HudunAnimation)
Copy after login

page: wxml:

<HudunAnimation tag="index" ref="hudunRef"></HudunAnimation>
Copy after login
// 进入页面时初始化动画
mounted() {
    this.$refs.hudunRef.init()
}
Copy after login

2. It can be noticed that among the components encapsulated above, there is a tag attribute, which is used to identify the animation instance from which page it comes from. It exists because in the component, under normal circumstances we can directly define a property in the data to store the animation instance, but after digging into the pit, we found that if we directly write

this.ins = lottie.loadAnimation({})
Copy after login

, the console will report an error because The object returned by lottie.loadAnimation({}) will go through a JSON.stringfy process when placed in data. During this process, an error is reported for unknown reasons. In order to solve this error, instead define an insList globally in the component to store the animation instance collection, get the corresponding page instance through the incoming tag, and then call the corresponding instance play method.

Page penetration and click issues

1. When dragging the page, it will cause the page to scroll. It is very simple to solve this problem. , just add

catchtouchmove="return"
Copy after login

in the area view

2. The problem of being unable to click and drag the area page button. First of all, our drag area is the entire page, and we use fixed positioning to cover the entire page, but this will cause the page under the mask layer to be unable to respond to click events. Therefore, we need to dynamically set the class name expand. When the element is in the dragging state, we will cover the masked area to the entire page, and the initial area can be consistent with the dragged element. For code implementation, see the complete code above

View the experience effect

WeChat search applet: Lobbyist English--your private foreign teacher

For more programming-related knowledge, please visit: Introduction to Programming! !

The above is the detailed content of How does uniapp implement the free drag and drop function on the mini program page?. 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)

How to start preview of uniapp project developed by webstorm How to start preview of uniapp project developed by webstorm Apr 08, 2024 pm 06:42 PM

Steps to launch UniApp project preview in WebStorm: Install UniApp Development Tools plugin Connect to device settings WebSocket launch preview

Which one is better, uniapp or mui? Which one is better, uniapp or mui? Apr 06, 2024 am 05:18 AM

Generally speaking, uni-app is better when complex native functions are needed; MUI is better when simple or highly customized interfaces are needed. In addition, uni-app has: 1. Vue.js/JavaScript support; 2. Rich native components/API; 3. Good ecosystem. The disadvantages are: 1. Performance issues; 2. Difficulty in customizing the interface. MUI has: 1. Material Design support; 2. High flexibility; 3. Extensive component/theme library. The disadvantages are: 1. CSS dependency; 2. Does not provide native components; 3. Small ecosystem.

What development tools do uniapp use? What development tools do uniapp use? Apr 06, 2024 am 04:27 AM

UniApp uses HBuilder

What basics are needed to learn uniapp? What basics are needed to learn uniapp? Apr 06, 2024 am 04:45 AM

uniapp development requires the following foundations: front-end technology (HTML, CSS, JavaScript) mobile development knowledge (iOS and Android platforms) Node.js other foundations (version control tools, IDE, mobile development simulator or real machine debugging experience)

What are the disadvantages of uniapp What are the disadvantages of uniapp Apr 06, 2024 am 04:06 AM

UniApp has many conveniences as a cross-platform development framework, but its shortcomings are also obvious: performance is limited by the hybrid development mode, resulting in poor opening speed, page rendering, and interactive response. The ecosystem is imperfect and there are few components and libraries in specific fields, which limits creativity and the realization of complex functions. Compatibility issues on different platforms are prone to style differences and inconsistent API support. The security mechanism of WebView is different from native applications, which may reduce application security. Application releases and updates that support multiple platforms at the same time require multiple compilations and packages, increasing development and maintenance costs.

Which is better, uniapp or native development? Which is better, uniapp or native development? Apr 06, 2024 am 05:06 AM

When choosing between UniApp and native development, you should consider development cost, performance, user experience, and flexibility. The advantages of UniApp are cross-platform development, rapid iteration, easy learning and built-in plug-ins, while native development is superior in performance, stability, native experience and scalability. Weigh the pros and cons based on specific project needs. UniApp is suitable for beginners, and native development is suitable for complex applications that pursue high performance and seamless experience.

What is the difference between uniapp and flutter What is the difference between uniapp and flutter Apr 06, 2024 am 04:30 AM

UniApp is based on Vue.js, and Flutter is based on Dart. Both support cross-platform development. UniApp provides rich components and easy development, but its performance is limited by WebView; Flutter uses a native rendering engine, which has excellent performance but is more difficult to develop. UniApp has an active Chinese community, and Flutter has a large and global community. UniApp is suitable for scenarios with rapid development and low performance requirements; Flutter is suitable for complex applications with high customization and high performance.

What component library does uniapp use to develop small programs? What component library does uniapp use to develop small programs? Apr 06, 2024 am 03:54 AM

Recommended component library for uniapp to develop small programs: uni-ui: Officially produced by uni, it provides basic and business components. vant-weapp: Produced by Bytedance, with a simple and beautiful UI design. taro-ui: produced by JD.com and developed based on the Taro framework. fish-design: Produced by Baidu, using Material Design design style. naive-ui: Produced by Youzan, modern UI design, lightweight and easy to customize.

See all articles