vue:异步async and await and generator与promise与this.nextTick()的使用

Vue.js与异步编程详解
本文深入探讨了Vue.js中的this.$nextTick()方法,解释了如何在DOM更新后执行回调,确保UI与数据同步。同时,文章通过具体示例讲解了ES6的generator、async/await以及Promise的使用技巧,帮助读者理解现代JavaScript异步编程的核心概念。

**this.nextTick()例子:**是在下次 DOM 更新循环结束之后执行延迟回调

    <template>
        <button ref="tar" type="button" name="button" @click="testClick">{{ content }}</button>
    </template>
    export default {
        data(){
            return {
                content: '初始值'
            }
        },
    methods: {
        testClick(){
              this.content = '改变了的值';
              // dom元素还未更新
              console.log(that.$refs.tar.innerText);//初始值
		this.$nextTick(() => {
                  // dom元素更新后执行
                  console.log(that.$refs.tar.innerText); //改变后的值
             })
       }
    }

this.$set 当点击后 匹配信息仍为上一个数值 会在事件的下一次空闲时间执行,不知道什么时候执行但是一定会执行

     <div class="type-list" v-for="(item,index) in specData">
        <div>{{item.name}}</div>
        <div>
          <span v-for="(item2,index2) in item.list" 
          @click="checkType(item,[index,index2])" 
          :class="item2.id === typeInfo[index].typeId?'active': ''">
          {{item2.item}}</span>
        </div>
    </div>

     checkType(data,index){
        this.$set(this.typeInfo[index[0]], 'name', data.name)
        this.$set(this.typeInfo[index[0]], 'id', data.id)
        this.$set(this.typeInfo[index[0]], 'typeId', data.list[index[1]].id)
        this.$set(this.typeInfo[index[0]], 'typeName', data.list[index[1]].item)
      },

async与await与generator 例子:
generator 是es6中新增的语法,和promise一样,都已用来异步编程

	function* test() {
        let a=1+2;
        yield 2;
        yield 3;
    }
    let b = test()
    console.log(b.next()); // > { value: 2, done: false } 
    console.log(b.next()); // > { value: 3, done: false }
    console.log(b.next()); // > { value: undefined, done: true }

加上*的函数自行后拥有了next函数,函数执行后返回一个对象。每次调用next函数可以继续执行被暂行的代码。
async 异步,会再最后执行

	async function timeout() {
	    return 'hello world'
	}
	console.log(timeout());
	console.log('先执行');

如果async 函数中有返回一个值 ,当调用该函数时,内部会调用Promise.solve() 方法把它转化成一个promise 对象作为返回

	async function timeout(flag) {
	    if (flag) {
	        return 'hello world'
	    } else {
	        throw 'my god, failure'
	    }
	}
    console.log(timeout(true))  // 调用Promise.resolve() 返回promise 对象。
    console.log(timeout(false)); // 调用Promise.reject() 返回promise 对象。

await

    async function testResult() {
        let first = await doubleAfter2seconds(30);
        let second = await doubleAfter2seconds(50);
        let third = await doubleAfter2seconds(30);
        console.log(first + second + third);
    }

6秒后,输出220
必须等完成后才执行下一步

promise
promise初始为pending状态,可以通过函数resolve和reject讲状态转变成resolved或者rejected状态,状一旦改变就不再变化。
then函数会返回一个promise实例,并且该返回值事一个新的实例而不是之前的实例。否则多个then调用就是去了意义
.all执行所有异步,返回给then,以最慢的为标准
.race 一样, 谁快谁先

项目例子:

    async focusInput (index) {
      await this.$nextTick(() => {
        let el = this.$refs[`scopeInput-${index}`].$el
        let input = el.querySelector('.el-input__inner')
        input.focus()
      })
    },
    
    <el-input
      @blur="blurInput"
      @keyup.native="enterInput"
      :ref="`scopeInput-${scope.$index}`"
      v-model="coursePrice"
      size="small">
    </el-input>
<template> <div class="navbar"> <hamburger id="hamburger-container" :is-active="sidebar.opened" class="hamburger-container" @toggleClick="toggleSideBar" /> <breadcrumb v-if="!topNav" id="breadcrumb-container" class="breadcrumb-container" /> <top-nav v-if="topNav" id="topmenu-container" class="topmenu-container" /> <div class="right-menu"> <template v-if="device!=='mobile'"> <search id="header-search" class="right-menu-item" /> <!-- <el-tooltip content="源码地址" effect="dark" placement="bottom"> <ruo-yi-git id="qiya-git" class="right-menu-item hover-effect" /> </el-tooltip> --> <!-- <el-tooltip content="文档地址" effect="dark" placement="bottom"> <ruo-yi-doc id="qiya-doc" class="right-menu-item hover-effect" /> </el-tooltip> --> <screenfull id="screenfull" class="right-menu-item hover-effect" /> <el-tooltip content="布局大小" effect="dark" placement="bottom"> <size-select id="size-select" class="right-menu-item hover-effect" /> </el-tooltip> </template> <el-dropdown class="avatar-container right-menu-item hover-effect" trigger="hover"> <div class="avatar-wrapper"> <img :src="avatar" class="user-avatar"> <span class="user-nickname"> {{ nickName }} </span> </div> <el-dropdown-menu slot="dropdown"> <router-link to="/user/profile"> <el-dropdown-item>个人中心</el-dropdown-item> </router-link> <el-dropdown-item divided @click.native="logout"> <span>退出登录</span> </el-dropdown-item> </el-dropdown-menu> </el-dropdown> <div class="right-menu-item hover-effect setting" @click="setLayout" v-if="setting"> <svg-icon icon-class="more-up" /> </div> </div> </div> </template> <script> import { mapGetters } from 'vuex' import Breadcrumb from '@/components/Breadcrumb' import TopNav from '@/components/TopNav' import Hamburger from '@/components/Hamburger' import Screenfull from '@/components/Screenfull' import SizeSelect from '@/components/SizeSelect' import Search from '@/components/HeaderSearch' import QiYaGit from '@/components/QiYa/Git' import QiYaDoc from '@/components/QiYa/Doc' export default { emits: ['setLayout'], components: { Breadcrumb, TopNav, Hamburger, Screenfull, SizeSelect, Search, QiYaGit, QiYaDoc }, computed: { ...mapGetters([ 'sidebar', 'avatar', 'device', 'nickName' ]), setting: { get() { return this.$store.state.settings.showSettings } }, topNav: { get() { return this.$store.state.settings.topNav } } }, methods: { toggleSideBar() { this.$store.dispatch('app/toggleSideBar') }, setLayout(event) { this.$emit('setLayout') }, logout() { this.$confirm('确定注销并退出系统吗?', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(async () => { try { // 1. 显示加载状态 const loadingInstance = this.$loading({ fullscreen: true }); // 2. 取消所有进行中的请求 if (this.$http.cancelAllRequests) { this.$http.cancelAllRequests('Operation canceled by logout'); } // 3. 执行退出操作 await this.$store.dispatch('LogOut'); // 4. 完全重置前端状态 this.resetApplicationState(); // 5. 导航到登录页(不刷新) await this.$router.push({ path: '/login', query: { logout: 'success', t: Date.now() // 防止缓存 } }); // 6. 显示退出成功消息 this.$message.success('您已安全退出系统'); } catch (error) { console.error('退出失败:', error); } finally { this.$nextTick(() => { loadingInstance.close(); }); } }).catch(() => {}); }, resetApplicationState() { // 清除所有存储 localStorage.clear(); sessionStorage.clear(); // 重置Vuex状态 this.$store.commit('RESET_ALL_STATE'); // 清除axios默认头 delete axios.defaults.headers.common['Authorization']; // 重置路由 this.$router.app.$options.router.matcher = new Router().matcher; } } } </script> <style lang="scss" scoped> .navbar { height: 50px; overflow: hidden; position: relative; background: #fff; box-shadow: 0 1px 4px rgba(0,21,41,.08); .hamburger-container { line-height: 46px; height: 100%; float: left; cursor: pointer; transition: background .3s; -webkit-tap-highlight-color:transparent; &:hover { background: rgba(0, 0, 0, .025) } } .breadcrumb-container { float: left; } .topmenu-container { position: absolute; left: 50px; } .errLog-container { display: inline-block; vertical-align: top; } .right-menu { float: right; height: 100%; line-height: 50px; &:focus { outline: none; } .right-menu-item { display: inline-block; padding: 0 8px; height: 100%; font-size: 18px; color: #5a5e66; vertical-align: text-bottom; &.hover-effect { cursor: pointer; transition: background .3s; &:hover { background: rgba(0, 0, 0, .025) } } } .avatar-container { margin-right: 0px; padding-right: 0px; .avatar-wrapper { margin-top: 10px; position: relative; .user-avatar { cursor: pointer; width: 30px; height: 30px; border-radius: 50%; } .user-nickname{ position: relative; bottom: 10px; font-size: 14px; font-weight: bold; } .el-icon-caret-bottom { cursor: pointer; position: absolute; right: -20px; top: 25px; font-size: 12px; } } } } } </style> 点击退出登录报错:退出失败: TypeError: Cannot read properties of undefined (reading 'cancelAllRequests') at eval (Navbar.vue:109:1) at Generator.eval (regenerator.js:52:1) at Generator.eval [as next] (regeneratorDefine.js:11:1) at asyncGeneratorStep (asyncToGenerator.js:3:1) at _next (asyncToGenerator.js:17:1) at eval (asyncToGenerator.js:22:1) at new Promise (<anonymous>) at eval (asyncToGenerator.js:14:1) overrideMethod @ hook.js:608 eval @ Navbar.vue:132 eval @ regenerator.js:52 eval @ regeneratorDefine.js:11 asyncGeneratorStep @ asyncToGenerator.js:3 _next @ asyncToGenerator.js:17 eval @ asyncToGenerator.js:22 eval @ asyncToGenerator.js:14 Promise.then logout @ Navbar.vue:103 click @ Navbar.vue:91 invokeWithErrorHandling @ vue.runtime.esm.js:1854 invoker @ vue.runtime.esm.js:2179 original._wrapper @ vue.runtime.esm.js:6917 Navbar.vue:106 [Vue warn]: Error in nextTick: "ReferenceError: loadingInstance is not defined" found in ---> <Navbar> at src/layout/components/Navbar.vue <Layout> at src/layout/index.vue <App> at src/App.vue <Root> overrideMethod @ hook.js:608 warn @ vue.runtime.esm.js:619 logError @ vue.runtime.esm.js:1884 globalHandleError @ vue.runtime.esm.js:1879 handleError @ vue.runtime.esm.js:1839 eval @ vue.runtime.esm.js:1982 flushCallbacks @ vue.runtime.esm.js:1906 Promise.then timerFunc @ vue.runtime.esm.js:1933 nextTick @ vue.runtime.esm.js:1990 Loading @ element-ui.common.js:28724 eval @ Navbar.vue:106 eval @ regenerator.js:52 eval @ regeneratorDefine.js:11 asyncGeneratorStep @ asyncToGenerator.js:3 _next @ asyncToGenerator.js:17 eval @ asyncToGenerator.js:22 eval @ asyncToGenerator.js:14 Promise.then logout @ Navbar.vue:103 click @ Navbar.vue:91 invokeWithErrorHandling @ vue.runtime.esm.js:1854 invoker @ vue.runtime.esm.js:2179 original._wrapper @ vue.runtime.esm.js:6917 Navbar.vue:106 ReferenceError: loadingInstance is not defined at VueComponent.eval (Navbar.vue:135:1) at Array.eval (vue.runtime.esm.js:1980:1) at flushCallbacks (vue.runtime.esm.js:1906:1)
最新发布
08-25
获取特勤线路详细信息失败 TypeError: _this6.$refs.mineMapRef.updateRealtimeRoute is not a function at _callee3$ (index.vue?./node_modules/babel-loader/lib/index.js!./node_modules/vue-loader/lib/index.js??vue-loader-options:701:39) at tryCatch (regeneratorRuntime.js:72:16) at Generator.eval (regeneratorRuntime.js:161:17) at Generator.eval [as next] (regeneratorRuntime.js:102:21) at asyncGeneratorStep (asyncToGenerator.js:9:24) at _next (asyncToGenerator.js:28:9)deviceArray: [__ob__: Observer] vue.js:4857 [Vue warn]: Error in v-on handler: "TypeError: Cannot read properties of undefined (reading 'realtime')" found in ---> <SpeLineList> at src/views/components/SpeLineDetail/index.vue <Index> at src/views/largeScreen/SpecialLine/index.vue <App> at src/views/App.vue <Root> warn$2 @ vue.js:4857 logError @ vue.js:3547 globalHandleError @ vue.js:3543 handleError @ vue.js:3511 invokeWithErrorHandling @ vue.js:3527 invoker @ vue.js:1461 invokeWithErrorHandling @ vue.js:3519 Vue.$emit @ vue.js:2638 _callee2$ @ index.vue?./node_modules/babel-loader/lib/index.js!./node_modules/vue-loader/lib/index.js??vue-loader-options:360 tryCatch @ regeneratorRuntime.js:72 eval @ regeneratorRuntime.js:161 eval @ regeneratorRuntime.js:102 asyncGeneratorStep @ asyncToGenerator.js:9 _next @ asyncToGenerator.js:28 Promise.then asyncGeneratorStep @ asyncToGenerator.js:18 _next @ asyncToGenerator.js:28 eval @ asyncToGenerator.js:33 Wrapper @ export.js:20 eval @ asyncToGenerator.js:25 submitForm @ index.vue?./node_modules/babel-loader/lib/index.js!./node_modules/vue-loader/lib/index.js??vue-loader-options:373 invokeWithErrorHandling @ vue.js:3519 invoker @ vue.js:1461 original_1._wrapper @ vue.js:7516 vue.js:3551 TypeError: Cannot read properties of undefined (reading 'realtime') at VueComponent.updateVehiclePosition (index.vue?./node_modules/babel-loader/lib/index.js!./node_modules/vue-loader/lib/index.js??vue-loader-options:475:19) at VueComponent.handlesHeadTq (index.vue?./node_modules/babel-loader/lib/index.js!./node_modules/vue-loader/lib/index.js??vue-loader-options:677:29) at VueComponent.handlestartTq (index.vue?./node_modules/babel-loader/lib/index.js!./node_modules/vue-loader/lib/index.js??vue-loader-options:668:12) at invokeWithErrorHandling (vue.js:3519:28) at VueComponent.invoker (vue.js:1461:16) at invokeWithErrorHandling (vue.js:3519:28) at Vue.$emit (vue.js:2638:11) at _callee2$ (index.vue?./node_modules/babel-loader/lib/index.js!./node_modules/vue-loader/lib/index.js??vue-loader-options:360:24) at tryCatch (regeneratorRuntime.js:72:16) at Generator.eval (regeneratorRuntime.js:161:17) 地图组件,父组件 // 特勤路线演习 handlestartTq(type) { this.deviceArray = [] console.log(this.deviceArray, 'aaaaaaaaaaaa'); console.log("type:", type, "deviceArray:", this.deviceArray); this.isStartTq=type this.handlesHeadTq() }, // 特勤路线演习-头车 handlesHeadTq() { console.log("deviceArray:", this.deviceArray); const dataPoints = this.deviceArray.map(item => ([ Number(item.longitude), Number(item.latitude) ])); this.$refs.mineMapRef.updateVehiclePosition(dataPoints[dataPoints.length - 1]) }, /** * @description:特勤线路详细信息 * @return {*} */ async handleTaskInfo(row) { try { const params = { id: row.id, }; const res = await getTqInfoApiBusiness(params); const dataPoints = res.data.xlData.map(item => ([ Number(item.longitude), Number(item.latitude) ])); this.$refs.mineMapRef.updateRealtimeRoute(dataPoints); this.$refs.mineMapRef.addRouteMarker(dataPoints[0], "end"); this.$refs.mineMapRef.addRouteMarker(dataPoints[dataPoints.length - 1], "start"); console.log(dataPoints, '获取特勤线路详细信息成功'); } catch (error) { console.log("获取特勤线路详细信息失败", error); } } //初始化MQTT initMQTT() { this.deviceArray = [] //开始链接MQTT const mqOptions = { clientId: new Date().getTime() + "", //客户端ID username: mqttUserName, //用户名 password: mqttUserPassword, //密码 keepalive: 30, //心跳时间 protocol: 'ws', //协议类型 reconnectPeriod: 30 * 1000, //两次重连间隔 connectTimeout: 40000, //重连超时时间 clean: true //设置为false,在离线时接收QoS 1和QoS 2消息 }; this.mqttClient = mqtt.connect(mqttAddress, mqOptions); // mqtt连接 this.mqttClient.on("connect", (e) => { this.mqttClient.subscribe('fusion-tqxl-gps', { qos: 0 }, (error) => { if (!error) { console.log('特勤路线【车载】订阅成功') } else { console.log('特勤路线【车载】订阅失败') } }) }); // 接收消息处理 this.mqttClient.on("message", (topic, message) => { const res = JSON.parse(message.toString()); // console.log("收到特勤路线【车载】00000", res) this.deviceArray.push(res) console.log("收到特勤路线【车载】", this.deviceArray) }); // 断开发起重连 this.mqttClient.on("reconnect", (error) => { console.log("特勤路线【车载】:", error); }); // 链接异常处理 this.mqttClient.on("error", (error) => { console.log("特勤路线【车载】:", error); }); },, watch: { deviceArray(newVal) { if (newVal.length > 0 && this.isStartTq) { this.handlesHeadTq(newVal) } }, },怎么修改报错,优化流程,在父组件获取到原路线先绘制 this.$refs.mineMapRef.updateRealtimeRoute(dataPoints); this.$refs.mineMapRef.addRouteMarker(dataPoints[0], "end"); this.$refs.mineMapRef.addRouteMarker(dataPoints[dataPoints.length - 1], "start");,在点击开始演习获取车辆实时位置handlestartTq,然后绘制新路线黄色,覆盖在原路线上,并且按照最新点位更新车辆图标
07-26
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值