This is the sixth day of my participation in the August More text Challenge. For details, see:August is more challenging

preface

In the last article, we talked about the basic configuration of Vue. With the configuration, we have to play with something. Today to make an event, don’t say much, straight to make.

To simplify things, you don’t have to introduce vue.js every time. So unless otherwise noted, this is all based on the following template for code demonstration, which we have already mentioned in the last article.

<! DOCTYPEhtml>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Document</title>
    <style></style>
</head>

<body>
    <! -- Introduction of Vue tripartite library -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

    <! Create a DOM element -->
    <div id="app"></div>

    <script>
    // Instantiate a Vue object
    // The Vue constructor receives the configuration object
    new Vue({
           el: '#app' // El specifies the DOM element of the page, and Vue will mount it to that DOM
    })
    </script>
</body>

</html>
Copy the code

The event processing

The concept in VUE is that you can bind event handlers to DOM elements via v-ON directives

Syntax V-ON: Event name =” JS expression”

<div id="app"<h2 v-on:click="count++">{{count}}</h2>
</div>

<script>
        new Vue({
            el: '#app'.data: {
                count: 17}})</script>
Copy the code

Notice v-ON: can be abbreviated as the @ sign

<div id="app">
        <h2 v-on:click="count++">{{count}}</h2>
        <button @click="count--">minus</button>
</div> 

<script>
        new Vue({
            el: '#app'.data: {
                count: 17}})</script>
Copy the code

— — — — — — — — — — — — notice — — — — — — — — — — — —

  1. In v-ON event binding, function names that are not explicitly added after () are implicitly added by vue by default, and will beEvent Event objectPassed as a parameter to the function
<div id="app">
        // When clicked, undefined is printed because the function does not pass any arguments
        <button @click="clickHandel()">click me</button>
        // When clicked, the event object is printed. Vue implicitly calls the function and passes event as an argument to the current function
        <button @click="clickHandel">click me</button>
</div>

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

<script>
        new Vue({
            el: '#app'.methods: {
                clickHandel(event) {
                    console.log(event)
                }
            }
        })
</script>
Copy the code
  1. If you need to pass not only the parameters but also the event object in the event binding function manually, you need to use the special variable $event provided by the vue instance object to manually pass the event object inside the function
<div id="app">
    // Pass the argument $event to the function manually, which is the special variable of the current event object provided by vue
    <button @click="clickHandel($event,12)">click me</button>
</div>

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

<script>
    new Vue({
        el: '#app'.methods: {
            clickHandel(event,num) {
                console.log(event,num)
            }
        }
    })
</script>
Copy the code

Vue instance object methods

The concept Vue constructor configuration option supports the Methods option, which mixes custom methods from the current instance into the Vue instance. These methods can be accessed directly through the Vue instance, or used in instruction expressions such as V-ON. The method defined by methods automatically binds this to the current Vue instance.

<div id="app">
    <h2 v-on:click="addCount()">{{count}}</h2>
    <button @click="minusCount()">minus</button>
    // In the v-on event binding, if the function name is not explicitly added (), the function name will be implicitly added () by default.
    <h2 v-on:click="addCount">{{count}}</h2>
    <button @click="minusCount">minus</button>
</div>

<script>
    new Vue({
        el: '#app'.data: {
            count: 17
        },
        methods: {
            addCount() {
                this.count += 2
            },
            minusCount() {
                this.count -= 2}}})</script>
Copy the code

Maybe this is not a very thorough example, but let’s do a classic example, what is it? That’s right, is to learn JS when wrote vomit round diagram. Isn’t it surprising and unexpected and exciting? That’s right! Today, let’s try a seamless rotation diagram. Maybe the style is not very beautiful ah, here we see the effect, the style can be back to slowly tinkered.

requirements

  • Realize seamless round diagram
  • Automatic wheel casting is not required.
  • The playround diagram contains two buttons next and prev for seamless playround
  • Seamless round diagram contains pages dots, the corresponding subscript dots will be highlighted

rendering

Basically, the comments are in the code, so we just put the code in. Knowledge points are mentioned in the instruction of the last article; Except for an @TransitionEnd event. In a word, in order to monitor the transition of animation is complete, you can go to the official website to consult or look up the novice tutorial, we will use here first.

<! DOCTYPEhtml>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            list-style: none;
        }

        .carousel-wrapper {
            position: relative;
            margin: 20px auto;
            width: 375px;
            height: 157.5 px.;
            border: 1px solid # 555;
            overflow: hidden;
        }

        .carousel {
            width: 1000%;
            height: 100%;
            font-size: 0;
        }

        .carousel li {
            display: inline-block;
            width: 10%;
            height: 100%;
        }

        .carousel li img {
            display: block;
            width: 100%;
            height: 100%;
        }

        .pages {
            display: flex;
            align-items: center;
            justify-content: space-around;
            position: absolute;
            bottom: 0;
            left: 80px;
            width: 200px;
            height: 20px;
            background-color: rgba(7.17.27.3);
        }

        .pages .dot {
            display: inline-block;
            width: 15px;
            height: 15px;
            border-radius: 50%;
            background-color: rgba(255.255.255.0.8);
        }

        .pages .dot.active {
            background-color: #fc0;
        }
    </style>
</head>

<body>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

    <div id="app">
        <div class="carousel-wrapper">
            <! > < span style = "box-sizing: border-box; color: RGB (51, 51, 51);
            <ul class="carousel" :style="{ transform: `translateX(${-10 * index}%)`, transition: needTransition ? 'all .5s linear' : 'none' }" @transitionend="transitionEndHandle">
                <! -- Replace the picture with your own picture -->
                <li>
                    <img src="./src/05.jpg">
                </li>
                <li>
                    <img src="./src/01.jpg">
                </li>
                <li>
                    <img src="./src/02.jpg">
                </li>
                <li>
                    <img src="./src/03.jpg">
                </li>
                <li>
                    <img src="./src/04.jpg">
                </li>
                <li>
                    <img src="./src/05.jpg">
                </li>
                <li>
                    <img src="./src/01.jpg">
                </li>
            </ul>
            <! -- Dot -->
            <ul class="pages">
                <! -- bind class -->
                <li class="dot" :class="{active: index === 1||index === 6}"></li>
                <li class="dot" :class="{active: index === 2}"></li>
                <li class="dot" :class="{active: index === 3}"></li>
                <li class="dot" :class="{active: index === 4}"></li>
                <li class="dot" :class="{active: index === 5||index === 0}"></li>
            </ul>
        </div>
        <div style="text-align: center;">
            <! -- Button for previous and next -->
            <button @click="prevPic">prev</button>
            <button @click="nextPic">next</button>
        </div>
    </div>

    <script>
        new Vue({
            el: '#app'.data: {
                index: 1.needTransition: true
            },
            methods: {
                // The next slide of the event
                nextPic() {
                    this.index++
                    this.needTransition = true
                },
                // The event in the last slide
                prevPic() {
                    this.index--
                    this.needTransition = true
                },
                // Animate the event
                transitionEndHandle() {
                    console.log('The transition is over')
                    // The last one without animation returns to the first one
                    if (this.index >= 6) {
                        this.index = 1
                        this.needTransition = false
                    }

                    // The first image has no animation
                    if (this.index <= 0) {
                        this.index = 5
                        this.needTransition = false}}}})</script>

</body>

</html>
Copy the code

The modifier

Concept event.preventDefault() or event.stopPropagation() are very common requirements in event handlers. Although we can easily do this in a method, it is better to have a method that has pure data logic instead of dealing with DOM event details. To solve this problem, vue.js provides an event modifier for V-on. Simplify the above DOM event detail requirements

Syntax V-ON: event name. Modifier 1. Modifier 2…

Event modifier

.stop Prevents event bubbles

<div id="app">

    <div :style="{width: '200px',height: '200px',backgroundColor: 'red'}" 
         @click="clickHandle($event,'div')">
        <p :style="{width: '120px',height: '120px',backgroundColor: 'green'}"
            @click.stop="clickHandle($event,'p')">
            <a @click.stop="clickHandle($event,'a')">This is label A</a>
        </p>
    </div>

</div>

<script>
    new Vue({
        el: '#app'.methods: {
            clickHandle(evet, detail) {
                console.log(detail + 'It was clicked', event.target)
            }
        }
    })
</script>
Copy the code

. Prevent Prevents the default event browser behavior

Prevent the default form submission behavior

<form>
    <input @click.prevent="clickHandle($event,'submit')" type="submit">
</form>
Copy the code

.capture Events use capture

<div :style="{width: '200px',height: '200px',backgroundColor: 'red'}" 
     @click.capture="clickHandle($event,'div')">
    <p :style="{width: '120px',height: '120px',backgroundColor: 'green'}"
       @click.capture="clickHandle($event,'p')">
        <a @click="clickHandle($event,'a')">This is label A</a>
    </p>
</div>
Copy the code

Self event. Target must be the element bound to the event itself to fire

<div :style="{width: '200px',height: '200px',backgroundColor: 'red'}" 
     @click="clickHandle($event,'div')">
    <p :style="{width: '120px',height: '120px',backgroundColor: 'green'}"
        @click.self="clickHandle($event,'p')">
        <a @click="clickHandle($event,'a')">This is label A</a>
    </p>
</div>
Copy the code

The. Once event is triggered only once

 <div :style="{width: '200px',height: '200px',backgroundColor: 'red'}" 
      @click="clickHandle($event,'div')">
    <p :style="{width: '120px',height: '120px',backgroundColor: 'green'}"
        @click.self.stop.once="clickHandle($event,'p')">
        <a @click="clickHandle($event,'a')">This is label A</a>
    </p>
</div>
Copy the code

. Passive Modifier that increases the sliding performance of scroll events on the mobile end. This modifier cannot be used with. Prevent

<! -- The default behavior of the scroll event (i.e., the scroll behavior) is triggered immediately -->
<! Without waiting for 'onScroll' to complete -->
<! -- this contains' event.preventdefault () '-->
<div v-on:scroll.passive="onScroll">.</div>
Copy the code

Key modifier

When listening for keyboard events, we often need to examine detailed keys. Vue allows v-On to add key modifiers when listening for keyboard events

V-on: indicates the name of an event. [event.key]

<! -- Press the keyboard s to trigger -->
<textarea @keyup.s="keyUpHandle"></textarea>
<! -- Press keyboard A to trigger -->
<textarea @keyup.a="keyUpHandle"></textarea>
<! -- Press keyboard A or S to trigger -->
<textarea @keyup.a.s="keyUpHandle"></textarea>
Copy the code

Note: In order to support older browsers if necessary, Vue provides aliases for most commonly used keycodes

  • enter
  • .tab
  • .delete (capture “Delete” and “backspace” keys)
  • .esc
  • .space
  • .up
  • .down
  • .left
  • .right

V-on: indicates the event name. System modification key.[event.key]

The system modifier can be used together with other keys to trigger the mouse or keyboard event listener when the corresponding key is pressed.

  • .ctrl
  • .alt
  • .shift
  • Meta On the Mac keyboard, Meta corresponds to the Command key (⌘). Meta on Windows keyboard corresponds to the Windows logo key (⊞). On the Sun OS keyboard, meta corresponds to the solid Gem key (◆). On other specific keyboards, especially those for MIT and Lisp machines, and their successors, such as the Knight keyboard and space-Cadet keyboard, meta is labeled “Meta.” On the Symbolics keyboard, meta is marked as either “meta” or “meta”.
// The shift key is held down and another key is pressed
<textarea @keyup.shift="keyUpHandle"></textarea>
// To trigger, press a after shift
<textarea @keyup.shift.a="keyUpHandle"></textarea>
// To trigger, press a after shift/CTRL
 <textarea @keyup.shift.ctrl.a="keyUpHandle"></textarea>
Copy the code

Note: VUE added the. Exact modifier in 2.5.0. This modifier provides strict control over the system modifier press

// Pressing the A key after holding shift/CTRL in non-strict mode will also trigger
<textarea @keyup.shift.a="keyUpHandle"></textarea>
// Pressing a after holding shift/CTRL in Strict mode does not trigger
// Pressing a will trigger only if shift is pressed and no other system modifier is pressed
<textarea @keyup.shift.a.exact="keyUpHandle"></textarea>
Copy the code

Mouse button modifier

The concept mouse modifier restricts the handler to responding only to a particular mouse button.

  • .left
  • .right
  • .middle

At the end

That’s all for today! See you next time! Code word is not easy, feel good can move little finger thumbs up what yo ~

series

Vue series

  • Starting Vue Configuration (1)
  • Vue Event Binding (2)
  • Vue components
  • Vue slot & filter
  • Vue backpass value ($EMIT event)

Vue – the Router series

  • Installation and use of vue-Router
  • Vue-router Routes configuration

Vuex series

  • Vuex series (I) — the use of Vuex
  • Vuex series (ii) — The use of modularity
  • Vuex Series (III) — the difference and usage of store.com MIT and Store. dispatch
  • Vuex series (IV) — Auxiliary function mapMutations analysis