chst365's blog chst365's blog
首页
  • Git
  • 网络
  • 操作系统
  • 浏览器
  • webpack
  • JavaScript
  • TypeScript
  • 性能
  • 工程化
  • React
  • 编程题
  • React技术揭秘
  • 算法
  • Node
  • 编码解码
  • NodeJS系列
  • Linux系列
  • JavaScript系列
  • HTTP系列
  • GIT系列
  • ES6系列
  • 设计模式系列
  • CSS系列
  • 小程序系列
  • 数据结构与算法系列
  • React系列
  • Vue3系列
  • Vue系列
  • TypeScript系列
  • Webpack系列
  • 分类
  • 标签
  • 归档
GitHub (opens new window)

chst365

DIV工程师
首页
  • Git
  • 网络
  • 操作系统
  • 浏览器
  • webpack
  • JavaScript
  • TypeScript
  • 性能
  • 工程化
  • React
  • 编程题
  • React技术揭秘
  • 算法
  • Node
  • 编码解码
  • NodeJS系列
  • Linux系列
  • JavaScript系列
  • HTTP系列
  • GIT系列
  • ES6系列
  • 设计模式系列
  • CSS系列
  • 小程序系列
  • 数据结构与算法系列
  • React系列
  • Vue3系列
  • Vue系列
  • TypeScript系列
  • Webpack系列
  • 分类
  • 标签
  • 归档
GitHub (opens new window)
  • NodeJS系列

  • Linux系列

  • JavaScript系列

  • HTTP系列

  • GIT系列

  • ES6系列

  • 设计模式系列

  • CSS系列

  • 小程序系列

  • 数据结构与算法系列

  • React系列

  • Vue3系列

  • Vue系列

    • vue项目本地开发完成后部署到服务器后报404是什么原因呢?
    • Vue项目中有封装过axios吗?主要是封装哪方面的?
    • 你了解axios的原理吗?有看过它的源码吗?
    • 双向数据绑定是什么
    • Vue组件之间的通信方式都有哪些?
    • Vue中组件和插件有什么区别?
    • Vue项目中你是如何解决跨域的呢?
    • 为什么data属性是一个函数而不是一个对象?
    • 动态给vue的data添加一个新的属性时会发生什么?怎样解决?
    • 你了解vue的diff算法吗?说说看
    • 你有写过自定义指令吗?自定义指令的应用场景有哪些?
    • 你是怎么处理vue项目中的错误的?
    • Vue中的过滤器了解吗?过滤器的应用场景有哪些?
    • SPA首屏加载速度慢的怎么解决?
    • v-if和v-for的优先级是什么?
    • 说说你对keep-alive的理解是什么?
    • 你知道vue中key的原理吗?说说你对它的理解
    • 请描述下你对vue生命周期的理解?在created和mounted这两个生命周期中请求数据有什么区别呢?
    • 说说你对vue的mixin的理解,有什么应用场景?
    • Vue常用的修饰符有哪些有什么应用场景
    • Vue实例挂载的过程
    • Vue中的$nextTick有什么作用?
    • Vue.observable你有了解过吗?说说看
      • 一、Observable 是什么
      • 二、使用场景
      • 三、原理分析
      • 参考文献
    • vue要做权限管理该怎么做?如果控制到按钮级别的权限怎么做?
    • v-show和v-if有什么区别?使用场景分别是什么?
    • 说说你对slot的理解?slot使用场景有哪些?
    • 你对SPA单页面的理解,它的优缺点分别是什么?如何实现SPA应用呢
    • SSR解决了什么问题?有做过SSR吗?你是怎么做的?
    • 说下你的vue项目的目录结构,如果是大型项目你该怎么划分结构和划分组件呢?
    • 什么是虚拟DOM?如何实现一个虚拟DOM?说说你的思路
    • 有使用过vue吗?说说你对vue的理解
    • vue3有了解过吗?能说说跟vue2的区别吗?
  • TypeScript系列

  • Webpack系列

  • 面试官
  • Vue系列
chst365
2023-06-28
目录

Vue.observable你有了解过吗?说说看

# 面试官:Vue.observable你有了解过吗?说说看

# 一、Observable 是什么

Observable 翻译过来我们可以理解成可观察的

我们先来看一下其在Vue中的定义

Vue.observable,让一个对象变成响应式数据。Vue 内部会用它来处理 data 函数返回的对象

返回的对象可以直接用于渲染函数和计算属性内,并且会在发生变更时触发相应的更新。也可以作为最小化的跨组件状态存储器

Vue.observable({ count : 1})
1

其作用等同于

new vue({ count : 1})
1

在 Vue 2.x 中,被传入的对象会直接被 Vue.observable 变更,它和被返回的对象是同一个对象

在 Vue 3.x 中,则会返回一个可响应的代理,而对源对象直接进行变更仍然是不可响应的

# 二、使用场景

在非父子组件通信时,可以使用通常的bus或者使用vuex,但是实现的功能不是太复杂,而使用上面两个又有点繁琐。这时,observable就是一个很好的选择

创建一个js文件

// 引入vue
import Vue from 'vue
// 创建state对象,使用observable让state对象可响应
export let state = Vue.observable({
  name: '张三',
  'age': 38
})
// 创建对应的方法
export let mutations = {
  changeName(name) {
    state.name = name
  },
  setAge(age) {
    state.age = age
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

在.vue文件中直接使用即可

<template>
  <div>
    姓名:{{ name }}
    年龄:{{ age }}
    <button @click="changeName('李四')">改变姓名</button>
    <button @click="setAge(18)">改变年龄</button>
  </div>
</template>
import { state, mutations } from '@/store
export default {
  // 在计算属性中拿到值
  computed: {
    name() {
      return state.name
    },
    age() {
      return state.age
    }
  },
  // 调用mutations里面的方法,更新数据
  methods: {
    changeName: mutations.changeName,
    setAge: mutations.setAge
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

# 三、原理分析

源码位置:src\core\observer\index.js

export function observe (value: any, asRootData: ?boolean): Observer | void {
  if (!isObject(value) || value instanceof VNode) {
    return
  }
  let ob: Observer | void
  // 判断是否存在__ob__响应式属性
  if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) {
    ob = value.__ob__
  } else if (
    shouldObserve &&
    !isServerRendering() &&
    (Array.isArray(value) || isPlainObject(value)) &&
    Object.isExtensible(value) &&
    !value._isVue
  ) {
    // 实例化Observer响应式对象
    ob = new Observer(value)
  }
  if (asRootData && ob) {
    ob.vmCount++
  }
  return ob
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

Observer类

export class Observer {
    value: any;
    dep: Dep;
    vmCount: number; // number of vms that have this object as root $data

    constructor (value: any) {
        this.value = value
        this.dep = new Dep()
        this.vmCount = 0
        def(value, '__ob__', this)
        if (Array.isArray(value)) {
            if (hasProto) {
                protoAugment(value, arrayMethods)
            } else {
                copyAugment(value, arrayMethods, arrayKeys)
            }
            this.observeArray(value)
        } else {
            // 实例化对象是一个对象,进入walk方法
            this.walk(value)
        }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

walk函数

walk (obj: Object) {
    const keys = Object.keys(obj)
    // 遍历key,通过defineReactive创建响应式对象
    for (let i = 0; i < keys.length; i++) {
        defineReactive(obj, keys[i])
    }
}
1
2
3
4
5
6
7

defineReactive方法

export function defineReactive (
  obj: Object,
  key: string,
  val: any,
  customSetter?: ?Function,
  shallow?: boolean
) {
  const dep = new Dep()

  const property = Object.getOwnPropertyDescriptor(obj, key)
  if (property && property.configurable === false) {
    return
  }

  // cater for pre-defined getter/setters
  const getter = property && property.get
  const setter = property && property.set
  if ((!getter || setter) && arguments.length === 2) {
    val = obj[key]
  }

  let childOb = !shallow && observe(val)
  // 接下来调用Object.defineProperty()给对象定义响应式属性
  Object.defineProperty(obj, key, {
    enumerable: true,
    configurable: true,
    get: function reactiveGetter () {
      const value = getter ? getter.call(obj) : val
      if (Dep.target) {
        dep.depend()
        if (childOb) {
          childOb.dep.depend()
          if (Array.isArray(value)) {
            dependArray(value)
          }
        }
      }
      return value
    },
    set: function reactiveSetter (newVal) {
      const value = getter ? getter.call(obj) : val
      /* eslint-disable no-self-compare */
      if (newVal === value || (newVal !== newVal && value !== value)) {
        return
      }
      /* eslint-enable no-self-compare */
      if (process.env.NODE_ENV !== 'production' && customSetter) {
        customSetter()
      }
      // #7981: for accessor properties without setter
      if (getter && !setter) return
      if (setter) {
        setter.call(obj, newVal)
      } else {
        val = newVal
      }
      childOb = !shallow && observe(newVal)
      // 对观察者watchers进行通知,state就成了全局响应式对象
      dep.notify()
    }
  })
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62

# 参考文献

  • https://blog.csdn.net/qq_32682301/article/details/105419673
  • https://wbbyouzi.com/archives/343
#面试官
上次更新: 2025/04/11, 17:57:53
Vue中的$nextTick有什么作用?
vue要做权限管理该怎么做?如果控制到按钮级别的权限怎么做?

← Vue中的$nextTick有什么作用? vue要做权限管理该怎么做?如果控制到按钮级别的权限怎么做?→

最近更新
01
面试官
03-27
02
this&指针&作用域&闭包
03-27
03
前端
03-27
更多文章>
Theme by Vdoing | Copyright © 2019-2025 chst365 | 豫ICP备17031889号-1
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式