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?

青灯夜游
Release: 2021-09-07 19:28:04
forward
8627 people have browsed it

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!

Related labels:
source:juejin.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template