Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Vue相关面试题 #134

Open
Popxie opened this issue Oct 28, 2021 · 0 comments
Open

Vue相关面试题 #134

Popxie opened this issue Oct 28, 2021 · 0 comments
Assignees

Comments

@Popxie
Copy link
Owner

Popxie commented Oct 28, 2021

Vue 相关面试题

1.下列代码会输出什么(字节)??

for (let i = 0; i < 10; i++) {
  this.a = i
  this.$nextTick(() => {
    console.log(this.a)
  })
}
// 10次9
  • 分析

    因为通过 this.$nextTick 注册的回调函数会被放到视图更新后的下一个事件循环执行、而 for 循环每次都是更改的 this 实例上的 a 属性的值、当 for 执行完后 this.a = 9在执行 this.$nextTick 注朋的回调函数的时候获取 this.a 的时候获取到的值也就是 9 了

2.页面渲染出来的值是什么?

<template>
  <div>{{a.b}}</div>
</template>

<script>
  export default {
    data() {
      return {
        a: {}
      }
    },
    created() {
      this.a.b = 1
    },
    mounted() {
      this.a.b = 2
    }
  }
</script>
  • 答案

    // vue3 之前
    1;
    // vue3
    2;
  • 分析

    涉及到两个知识点,一个是 vue 响应式原理,一个是
    created 和 mounted 两个生命周期的区别。

    • 1 . Vue 无法检测 property 的添加或移除。由于 Vue会在初始化实例时对 property 执行getter/setter 转化,所以 property 必须在 data 对象上存在才能让 Vue 将它转换为响应式的。所以 this.a.b 中的 b 是非响应式的

    • 2 .又因为在 created 视图未渲染时直接对对象 a的属性 b 赋值 data 里面的初值会改变的,但是在 mounted 里面更新 this.a.b 的值的时候是非响应式的,所以视图不会更新。注意,Vue3 之后采用了 proxy 方式,所以 Vue3 版本会渲染出 2

@Popxie Popxie self-assigned this Oct 28, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant