Vue 最新面试题

$nextTick 原理

概括

vue 实现响应式并不是数据发生变化后 DOM 立即变化。vue 在修改数据后,要等到同一事件循环机制内所有数据变化完成后,再统一进行 DOM 更新

nextTick 可以让我们在下次 DOM 更新循环结束后执行延迟回调,用于获取更新后的 DOM

原理

Vue 中数据变化到 DOM 变化是异步过程,一旦观察到数据变化,Vue 就会开启一个任务队列,然后把在同一个事件循环中观察到的数据变化的 Watcher(Vue 源码中的 Watcher 类是用来更新 Dep 类收集到的依赖的)推送到这个队列中

如果这个 Watcher 被触发多次,只会被推送到队列一次。这种缓冲行为可以有效的去掉重复数据造成的不必要的计算和 DOM 操作。而在下一个事件循环时,Vue 会被清空队列,并进行必要的 DOM 更新

nextTick 的作用就是为了在数据变化之后等待 Vue 完成更新 DOM,可以在数据变化之后立即执行Vue.nextTick(callback) 中的回调函数

JS 是单线程的,拥有事件循环机制,nextTick 的实现就是利用了事件循环的宏任务和微任务

目前浏览器平台并没有实现 nextTick 方法,所以 Vue.js 源码中分别用 Promise、setTimeout、setImmediate 等方式在 microtask(或是 task)中创建一个事件,目的是在当前调用栈执行完毕以后(不一定立即)才会执行这个事件

nextTick 调用方式

  • 回调函数方式:Vue.nextTick(callback)
  • Promise 方式:Vue.nextTick().then(callback)
  • 实例方式:vm.$nextTick(callback)

nextTick 应用

  • created 生命周期中操作 DOM
  • 修改数据,获取 DOM 值

事件循环机制

在浏览器环境中,我们可以将要执行的任务分为宏任务和微任务

宏任务:整体代码 script、setTimeout、setInterval、setImmediate

微任务:Promise.then、Promise.all

加载 js 代码,先执行同步任务,异步任务放入异步队列中

对于异步队列中的任务,先执行 script,然后执行微任务。当所有的微任务执行完毕,执行下一个宏任务

先同后异,先微后宏

由于 DOM 操作资源消耗大,因此并不是每次数据改变都触发 watcher 的回调,而是先将这些 watcher 添加到一个队列 queueWatcher(队列中) 中,然后在 nextTick 后执行 flushSchedulerQueue(刷新调度程序队列) 处理

computed 缓存

computed 是响应式的,读取时会触发 get,设置时会触发 set

computed 控制缓存

某个计算属性 C 依赖 data 中的 A,如果没有缓存,每次读取 C 时,C 都会读取 A,就会触发 A 的 get,多次触发 A 的 get 资源消耗大,所以 computed 设置了缓存

控制缓存的关键:脏数据标记 dirty,dirty 是 watcher 的属性

  • dirty 为 true 时,读取 computed 值时重新计算
  • dirty 为 false 时,读取 computed 值时会使用缓存

依赖数据发生改变,computed 更新

页面 P 中的计算属性 C,依赖于 data 里的 A,computed 的更新步骤:

  • 因为 C 依赖于 A,所以 A 可以收集到 C 的 watcher
  • 当 A 发生改变时,会将计算属性 C 的 watcher 的属性 dirty 设置为 true
  • A 还会收集到页面 P 的 watcher,同时 A 会通知 P 进行更新,页面 P 重新读取计算属性 C。由于此时的 dirty 为 true,所以计算属性会重新计算
  • computed 更新完成后,会将 dirty 设置为 false
  • 如果依赖的 A 没有发生改变,那么下次就会读取缓存
javascript 复制代码
function createComputedGetter(key) {
  // 获取到相应 key 的 computed-watcher
  let watcher = this._computedWatchers[key]
  // 如果 computed 依赖的数据变化,dirty 会变成 true
  // 从而重新计算,然后更新缓存值 watcher.value
  if (watcher.dirty) {
    watcher.evaluate()
  }
  // computed 的关键,让双方建立关系
  if (Dep.target) {
    watcher.depend()
  }
  return watcher.value
}

封装全局弹窗组件

html 复制代码
<!-- Box.vue -->
<template>
  <div class="box" v-if="isShow">
    <div>
      <!-- 标题和描述 -->
      <div>{{ text.title }}</div>
      <div>{{ text.msg }}</div>
      <!-- 确认和取消 -->
      <div @click="confirm">
        <span>{{ text.btn.confirmVal }}</span>
      </div>
      <div @click="cancel">
        <span>{{ text.btn.cancelVal }}</span>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      isShow: true,
      text: {
        title: '提示',
        msg: '描述信息',
        cancelBtn: true,
        confirmBtn: true,
        btn: {
          confirmVal: '确定',
          cancelVal: '取消',
        },
      },
    }
  },
  methods: {
    confirm() {
      this.isShow = false
    },
    cancel() {
      this.isShow = false
    },
  },
}
</script>
javascript 复制代码
// box.js
import Vue from 'vue'
import confirm from '../components/Box.vue'

let confirmConstructor = Vue.extend(confirm)

let theConfirm = function (text) {
  return new Promise((resolve, reject) => {
    let confirmDom = new confirmConstructor({
      el: document.createElement('div'),
    })
    // new 一个对象,然后插入 body 中
    document.body.appendChild(confirmDom.$el)
    confirmDom.text = Object.assign({}, confirmDom.text, text)
    confirmDom.confirm = function () {
      confirmDom.isShow = false
      resolve('确认')
    }
    confirm.cancel = function () {
      confirmDom.isShow = false
      reject('取消')
    }
  })
}

export default theConfirm
javascript 复制代码
// main.js
import myConfirm from '@/assets/box'
Vue.prototype.$myConfirm = myConfirm
html 复制代码
<!-- Home.vue -->
<template>
  <div class="home">
    <button @click="openConfirmBox">弹出弹窗</button>
  </div>
</template>

<script>
export default {
  methods: {
    openConfirmBox() {
      this.$myConfirm({
        title: '退出',
        msg: '确认要退出吗?',
        btn: {
          confirmVal: '确定',
          cancelVal: '取消',
        },
      })
        .then((res) => {
          console.log('yes', res)
        })
        .catch((err) => {
          console.log('no', err)
        })
    },
  },
}
</script>

实现组织架构图

安装依赖

bash 复制代码
npm install less
npm install --save-dev less-loader
npm install vue-tree-color

引入依赖

javascript 复制代码
// main.js
import Vue2OrgTree from 'vue-tree-color'
Vue.use(Vue2OrgTree)

相关属性

修改排列方式

html 复制代码
<!-- 默认值为 false,横向展示,值为 true 时纵向展示 -->
<vue2-org-tree :horizontal="true"/>

折叠展示效果

html 复制代码
<!-- 开始折叠展示效果 -->
<vue2-org-tree collapsable/>

展开方式

html 复制代码
<vue2-org-tree collapsable @on-expand="onExpand"/>
<script>
export default {
  methods: {
    // 判断子分类是否打开
    onExpand(e, data) {
      if ('expand' in data) {
        data.expand = !data.expand
        if (!data.expand && data.children) {
          this.collapse(data.children)
        }
      } else {
        this.$set(data, 'expand', true)
      }
    },
    collapse(list) {
      let _this = this
      list.forEach(function (child) {
        if (child.expand) {
          child.expand = false
        }
        child.children && _this.collapse(child.children)
      })
    },
  },
}
</script>

默认展开

在请求完数据后直接调用,或生命周期调用

第一个参数是资源 data,第二个参数是是否全部展开(true 展开,false 不展开)

javascript 复制代码
created() {
  this.toggleExpand(this.obj, false)
},
methods: {
  toggleExpand(data, val) {
    let _this = this
    if (Array.isArray(data)) {
      data.forEach(function (item) {
        _this.$set(item, 'expand', val)
        if (item.children) {
          _this.toggleExpand(item.children, val)
        }
      })
    } else {
      this.$set(data, 'expand', val)
      if (data.children) {
        _this.toggleExpand(data.children, val)
      }
    }
  },
},

使用

html 复制代码
<template>
  <div>
    <vue2-org-tree
      :data="obj"
      :horizontal="true"
      :label-class-name="labelClassName"
      collapsable
      @on-expand="onExpand"
    />
  </div>
</template>

<script>
export default {
  data() {
    return {
      labelClassName: 'bg-color-orange',
      obj: {
        id: 0,
        label: '神州行',
        children: [
          {
            id: 2,
            label: '产品研发部',
            children: [
              {
                id: 5,
                label: '研发-前端',
              },
              {
                id: 6,
                label: '研发-后端',
              },
              {
                id: 7,
                label: 'UI 设计',
              },
            ],
          },
        ],
      },
    }
  },
  created() {
    this.toggleExpand(this.obj, false)
  },
  methods: {
    onExpand(e, data) {
      if ('expand' in data) {
        data.expand = !data.expand
        if (!data.expand && data.children) {
          this.collapse(data.children)
        }
      } else {
        this.$set(data, 'expand', true)
      }
    },
    collapse(list) {
      let _this = this
      list.forEach(function (child) {
        if (child.expand) {
          child.expand = false
        }
        child.children && _this.collapse(child.children)
      })
    },
    toggleExpand(data, val) {
      let _this = this
      if (Array.isArray(data)) {
        data.forEach(function (item) {
          _this.$set(item, 'expand', val)
          if (item.children) {
            _this.toggleExpand(item.children, val)
          }
        })
      } else {
        this.$set(data, 'expand', val)
        if (data.children) {
          _this.toggleExpand(data.children, val)
        }
      }
    },
  },
}
</script>
相关推荐
拿不拿铁1943 分钟前
Vite 5.x 开发模式启动流程分析
前端
fruge1 小时前
设计稿还原技巧:解决间距、阴影、字体适配的细节问题
前端·css
把csdn当日记本的菜鸡1 小时前
js查缺补漏
开发语言·javascript·ecmascript
BBB努力学习程序设计1 小时前
了解响应式Web设计:viewport网页可视区域
前端·html
zhangyao9403301 小时前
uni-app scroll-view特定情况下运用
前端·javascript·uni-app
码农张1 小时前
从原理到实践,吃透 Lit 响应式系统的核心逻辑
前端
jump6801 小时前
object和map 和 WeakMap 的区别
前端
打小就很皮...1 小时前
基于 Dify 实现 AI 流式对话:组件设计思路(React)
前端·react.js·dify·流式对话
这个昵称也不能用吗?1 小时前
【安卓 - 小组件 - app进程与桌面进程】
前端
kuilaurence2 小时前
CSS `border-image` 给文字加可拉伸边框
前端·css