Home  >  Article  >  Web Front-end  >  [Organization and Sharing] Essential operating skills for Vue development, come and collect them!

[Organization and Sharing] Essential operating skills for Vue development, come and collect them!

青灯夜游
青灯夜游forward
2022-07-21 20:13:191808browse

Mastering more skills will increase your programming efficiency. If you want to do your job well, you must first sharpen your tools. This article will share with you some essential Vue operation skills. I hope it will be helpful to you!

[Organization and Sharing] Essential operating skills for Vue development, come and collect them!(Learning video sharing:

vue video tutorial

)

Keyboard events

  • In js we usually bind an event to get the code of the key, and then pass ## in event #keyCode Attribute to get the code
  • If we need to implement a fixed key to trigger the event, we need to constantly judge, which is actually very troublesome
let button = document.querySelector('button')

button.onkeyup = function (e) {
    console.log(e.key)
    if (e.keyCode == 13) {
        console.log('我是回车键')
    }
}
  • vue provides aliases for some commonly used keys. We only need to add the response alias after the event.
  • vue Common aliases are: up/ Up arrow, down/down arrow, left/left arrow, right/right arrow, space/space, tab/line feed, esc/exit, enter/carriage return, delete/delete
// 只有按下回车键时才会执行 send 方法
<input v-on:keyup.enter="send" type="text">
    For keys that do not provide aliases in
  • Vue, you can use the original key value to bind. The so-called key value is event.key Obtained value
  • If the
  • key value is a single letter, you can use it directly. If it is a camel case name consisting of multiple words, you need to split it and use - Connection
// 只有按下q键时才会执行send方法
<input v-on:keyup.Q="send" type="text">

// 只有按下capslock键时才会执行send方法
<input v-on:keyup.caps-lock="send" type="text">
    For system modifiers
  • ctrl, alt, shift these comparisons For the use of complex keys, there are two situations
  • Because these keys can be pressed while pressing other keys to form a combination shortcut key
  • When the trigger event is
  • keydown , we can directly press the modifier to trigger
  • When the trigger event is
  • keyup, when pressing the modifier key, press other keys at the same time, and then release other keys , the event can be triggered.
// keydown事件时按下alt键时就会执行send方法
<input v-on:keydown.Alt="send" type="text">

// keyup事件时需要同时按下组合键才会执行send方法
<input v-on:keyup.Alt.y="send" type="text">
    Of course we can also customize the key alias
  • through
  • Vue.config.keyCodes. Custom key name = key code Define
// 只有按下回车键时才会执行send方法
<input v-on:keydown.autofelix="send" type="text">
    
// 13是回车键的键码,将他的别名定义为autofelix
Vue.config.keyCodes.autofelix=13
Picture preview

    We often need to use picture preview in projects,
  • viewerjs is a very cool picture preview Plug-in
  • Function support includes image enlargement, reduction, rotation, dragging, switching, stretching, etc.
  • Installation
  • viewerjsExtension
npm install viewerjs --save
    Introduce and configure the function
//引入
import Vue from 'vue';
import 'viewerjs/dist/viewer.css';
import Viewer from 'v-viewer';

//按需引入
Vue.use(Viewer);

Viewer.setDefaults({
    'inline': true,
    'button': true, //右上角按钮
    "navbar": true, //底部缩略图
    "title": true, //当前图片标题
    "toolbar": true, //底部工具栏
    "tooltip": true, //显示缩放百分比
    "movable": true, //是否可以移动
    "zoomable": true, //是否可以缩放
    "rotatable": true, //是否可旋转
    "scalable": true, //是否可翻转
    "transition": true, //使用 CSS3 过度
    "fullscreen": true, //播放时是否全屏
    "keyboard": true, //是否支持键盘
    "url": "data-source",
    ready: function (e) {
        console.log(e.type, '组件以初始化');
    },
    show: function (e) {
        console.log(e.type, '图片显示开始');
    },
    shown: function (e) {
        console.log(e.type, '图片显示结束');
    },
    hide: function (e) {
        console.log(e.type, '图片隐藏完成');
    },
    hidden: function (e) {
        console.log(e.type, '图片隐藏结束');
    },
    view: function (e) {
        console.log(e.type, '视图开始');
    },
    viewed: function (e) {
        console.log(e.type, '视图结束');
        // 索引为 1 的图片旋转20度
        if (e.detail.index === 1) {
            this.viewer.rotate(20);
        }
    },
    zoom: function (e) {
        console.log(e.type, '图片缩放开始');
    },
    zoomed: function (e) {
        console.log(e.type, '图片缩放结束');
    }
})
    Use the picture preview plug-in
  • Use a single picture
<template>
  <div>
    <viewer>
      <img :src="cover" style="cursor: pointer;" height="80px">
    </viewer>
  </div>
</template>
 
<script>
export default {
  data() {
    return {
      cover: "//www.autofelix.com/images/cover.png"
    }
  }
}
</script>
    Use multiple pictures
<template>
  <div>
    <viewer :images="imgList">
      <img v-for="(imgSrc, index) in imgList" :key="index" :src="imgSrc" />
    </viewer>
  </div>
</template>
 
<script>
export default {
  data() {
    return {
      imgList: [
        "//www.autofelix.com/images/pic_1.png",
        "//www.autofelix.com/images/pic_2.png",
        "//www.autofelix.com/images/pic_3.png",
        "//www.autofelix.com/images/pic_4.png",
        "//www.autofelix.com/images/pic_5.png"
      ]
    }
  }
}
</script>
Marquee

    This is a fun special effects technique
  • For example, when you pick up people at the airport, you can use the marquee special effects on your mobile phone. Become the most handsome boy in the crowd
  • The marquee special effect is actually to delete the first text and add it to the last one, thus forming the effect of text movement
<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>跑马灯</title>
    <style type="text/css">
        #app {
            padding: 20px;
        }
    </style>
</head>

<body>
    <div id="app">
        <button @click="run">应援</button>
        <button @click="stop">暂停</button>
        <h3>{{ msg }}</h3>
    </div>
</body>
<script src="https://cdn.jsdelivr.net/npm/vue@2.7.0/dist/vue.min.js"></script>
<script>
    new Vue({
        el: "#app",
        data: {
            msg: "飞兔小哥,飞兔小哥,我爱飞兔小哥~~~",
            timer: null // 定时器
        },
        methods: {
            run() {
                // 如果timer已经赋值就返回
                if (this.timer) return;

                this.timer = setInterval(() => {
                    // msg分割为数组
                    var arr = this.msg.split('');
                    // shift删除并返回删除的那个,push添加到最后
                    // 把数组第一个元素放入到最后面
                    arr.push(arr.shift());
                    // arr.join('')吧数组连接为字符串复制给msg
                    this.msg = arr.join('');
                }, 100)
            },
            stop() {
                //清除定时器
                clearInterval(this.timer);
                //清除定时器之后,需要重新将定时器置为null
                this.timer = null;
            }
        }
    })
</script>

</html>
Countdown

    There are many applications for the countdown technique
  • For example, when there are many rush-buying products, we need to have a countdown to remind users of the time to start the rush
  • In fact, it is every other Seconds, recalculate the time and assign it to
  • DOM
<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>倒计时</title>
</head>

<body>
    <div id="app">
        <div>抢购开始时间:{{count}}</div>
    </div>
</body>
<script src="https://cdn.jsdelivr.net/npm/vue@2.7.0/dist/vue.min.js"></script>
<script>
    new Vue({
        el: "#app",
        data() {
            return {
                count: '', //倒计时
                seconds: 864000 // 10天的秒数
            }
        },
        mounted() {
            this.Time() //调用定时器
        },
        methods: {
            // 天 时 分 秒 格式化函数
            countDown() {
                let d = parseInt(this.seconds / (24 * 60 * 60))
                d = d < 10 ? "0" + d : d
                let h = parseInt(this.seconds / (60 * 60) % 24);
                h = h < 10 ? "0" + h : h
                let m = parseInt(this.seconds / 60 % 60);
                m = m < 10 ? "0" + m : m
                let s = parseInt(this.seconds % 60);
                s = s < 10 ? "0" + s : s
                this.count = d + &#39;天&#39; + h + &#39;时&#39; + m + &#39;分&#39; + s + &#39;秒&#39;
            },
            //定时器没过1秒参数减1
            Time() {
                setInterval(() => {
                    this.seconds -= 1
                    this.countDown()
                }, 1000)
            },
        }
    })
</script>

</html>
Customized right-click menu

    In the project, we sometimes You need to customize the options that appear with the right mouse button instead of the browser's default right-click options
  • How to implement the right-click menu is actually very simple in
  • Vue, just use vue-contextmenujs Plug-in can be installed
  • vue-contextmenujs Plug-in
npm install vue-contextmenujs
    Introduction
//引入
import Vue from 'vue';
import Contextmenu from "vue-contextmenujs"

Vue.use(Contextmenu);
    How to use
  • You can use
  • You can add icons to options
  • You can use
  • style Style of label customization option
  • You can use
  • disabled You can click the attribute to disable the option
  • You can use
  • divided:true Set the underline of the option
  • You can use
  • children to set sub-options
<style>
    .custom-class .menu_item__available:hover,
    .custom-class .menu_item_expand {
        background: lightblue !important;
        color: #e65a65 !important;
    }
</style>


<template>
    <div style="width:100vw;height:100vh" @contextmenu.prevent="onContextmenu"></div>
</template>

<script>
    import Vue from 'vue'
    import Contextmenu from "vue-contextmenujs"
    Vue.use(Contextmenu);

    export default {
        methods: {
            onContextmenu(event) {
                this.$contextmenu({
                    items: [
                        {
                            label: "返回",
                            onClick: () => {
                                // 添加点击事件后的自定义逻辑
                            }
                        },
                        { label: "前进", disabled: true },
                        { label: "重载", divided: true, icon: "el-icon-refresh" },
                        { label: "打印", icon: "el-icon-printer" },
                        {
                            label: "翻译",
                            divided: true,
                            minWidth: 0,
                            children: [{ label: "翻译成中文" }, { label: "翻译成英文" }]
                        },
                        {
                            label: "截图",
                            minWidth: 0,
                            children: [
                                {
                                    label: "截取部分",
                                    onClick: () => {
                                        // 添加点击事件后的自定义逻辑
                                    }
                                },
                                { label: "截取全屏" }
                            ]
                        }
                    ],
                    event, // 鼠标事件信息
                    customClass: "custom-class", // 自定义菜单 class
                    zIndex: 3, // 菜单样式 z-index
                    minWidth: 230 // 主菜单最小宽度
                });
                return false;
            }
        }
    };
</script>
Print function

    Supports printing function for web pages, which is also common in many projects
  • To use the printing function in Vue, you can use the
  • vue-print-nb plug-in
  • installation
  • vue-print-nb plug-in
npm install vue-print-nb --save
    Introducing printing service
import Vue from 'vue'
import Print from 'vue-print-nb'
Vue.use(Print);
    Use
  • Use the
  • v-print command to start the printing function
<div id="printStart">
    <p>红酥手,黄縢酒,满城春色宫墙柳。</p>
    <p>东风恶,欢情薄。</p>
    <p>一怀愁绪,几年离索。</p>
    <p>错、错、错。</p>
    <p>春如旧,人空瘦,泪痕红浥鲛绡透。</p>
    <p>桃花落,闲池阁。</p>
    <p>山盟虽在,锦书难托。</p>
    <p>莫、莫、莫!</p>
</div>
<button v-print="&#39;#printStart&#39;">打印</button>
JSONP request

  • jsonp is one of the main ways to solve cross-domain issues
  • So learn how to It is actually very important to use
  • jsonp in vue
  • Installation
  • jsonpExtension
npm install vue-jsonp --save-dev
    Registration Service
// 在vue2中注册服务
import Vue from 'vue'
import VueJsonp from 'vue-jsonp'
Vue.use(VueJsonp)

// 在vue3中注册服务
import { createApp } from 'vue'
import App from './App.vue'
import VueJsonp from 'vue-jsonp'
createApp(App).use(VueJsonp).mount('#app')
    Usage method
  • It should be noted that after using
  • jsonp to request data, the callback is not then Instead of executing
  • in the custom
  • callbackName, it needs to be mounted on the window object
<script>
export default {
  data() {...},
  created() {
    this.getUserInfo()
  },
  mounted() {
    window.jsonpCallback = (data) => {
        // 返回后回调
        console.log(data)
    }
  },
  methods: {
    getUserInfo() {
     this.$jsonp(this.url, {
      callbackQuery: "callbackParam",
      callbackName: "jsonpCallback"
     })
      .then((json) => {
          // 返回的jsonp数据不会放这里,而是在 window.jsonpCallback
          console.log(json)
      })  
    }
  }
 }
</script>
【 Related video tutorial recommendations:

vuejs entry tutorial, web front-end entry

The above is the detailed content of [Organization and Sharing] Essential operating skills for Vue development, come and collect them!. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete