vue中怎么实现观察者模式,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。
成都创新互联主要从事做网站、网站建设、网页设计、企业做网站、公司建网站等业务。立足成都服务和龙,10余年网站建设经验,价格优惠、服务专业,欢迎来电咨询建站服务:028-86922220
1 响应式原理
让我们先从相应式原理开始。我们可以通过Object.defineProterty()来自定义Object的getter和setter 从而达到我们的目的。
代码如下
function observe(value, cb) {
Object.keys(value).forEach((key) => defineReactive(value, key, value[key] , cb))
}
function defineReactive (obj, key, val, cb) {
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get: ()=>{
/*....依赖收集等....*/
/*Github:https://github.com/answershuto*/
return val
},
set:newVal=> {
val = newVal;
cb();/*订阅者收到消息的回调*/
}
})
}
class Vue {
constructor(options) {
this._data = options.data;
observe(this._data, options.render)
}
}
let app = new Vue({
el: '#app',
data: {
text: 'text',
text2: 'text2'
},
render(){
console.log("render");
}
})通过observe函数对app.data上的每一个key和value都设定getter和setter。当value改变的时候触发setter,就会触发render这个函数。响应式的目的就达成,如果是视图更新的话我们通过监听dom的input事件来触发数据更新
但是现在我们只有在改变vue._data.text的时候才会触发他们的setter,但是我想偷懒,只改变vue.text就能触发到setter怎么做呢?
我们使用代理的方法
_proxy.call(this, options.data);/*构造函数中*/
/*代理*/
function _proxy (data) {
const that = this;
Object.keys(data).forEach(key => {
Object.defineProperty(that, key, {
configurable: true,
enumerable: true,
get: function proxyGetter () {
return that._data[key];
},
set: function proxySetter (val) {
that._data[key] = val;
}
})
});
}依赖收集
让我们再来看看下面的代码
new Vue({
template:
`
text1: {{text1}}
text2: {{text2}}
`,
data: {
text1: 'text1',
text2: 'text2',
text3: 'text3'
}
});
当你的text3变化的时候,实际上text3并没有被渲染,但是也会触发一次render函数,这显然是不对的。所以我们需要收集依赖。
我们只需要在初始化的时候渲染一遍,那所有渲染所依赖的数据都会被触发getter,这时候我们只要把这个数据放到一个列表里就好啦!
我们先来认识一下Dep(dependencies)这个类,下图是一个最简单的Dep类。我们可以把他理解为发布者(这点很重要!!)
class Dep {
constructor () {
this.subs = [];
}
addSub (sub: Watcher) {
this.subs.push(sub)
}
removeSub (sub: Watcher) {
remove(this.subs, sub)
}
/*Github:https://github.com/answershuto*/
notify () {
// stabilize the subscriber list first
const subs = this.subs.slice()
for (let i = 0, l = subs.length; i < l; i++) {
subs[i].update()
}
}
}
function remove (arr, item) {
if (arr.length) {
const index = arr.indexOf(item)
if (index > -1) {
return arr.splice(index, 1)
}
}我们每次触发getter的时候,只要把触发的对象放到dep.sub里面就好啦!
但是现在问题来了,我们用什么来装这个触发的'对象',也可以说式订阅者呢?
我们使用Watcher这个类
class Watcher {
constructor (vm, expOrFn, cb, options) {
this.cb = cb;
this.vm = vm;
/*在这里将观察者本身赋值给全局的target,只有被target标记过的才会进行依赖收集*/
Dep.target = this;
/*Github:https://github.com/answershuto*/
/*触发渲染操作进行依赖收集*/
this.cb.call(this.vm);
}
update () {
this.cb.call(this.vm);
}
}vm即是vue实例, expOrFn就是{{a+b}}里面的a+b, cb就是回调函数就是return a+b, options是一些配置项。
Vue在第一次渲染列表的时候如果碰到{{xxx}}这样的表达式,就会new Watcher()。解析里面的函数,然后把当前的watcher实例赋给Dep.target(Dep.target是全局的,一次性只能有一个存在,因为Vue一次只处理一个依赖)。然后执行回调函数。(这里看似是执行回调函数渲染,其实又触发了一次getter,然后就会把当前的依赖添加到sub里去)
接下来开始依赖收集
class Vue {
constructor(options) {
this._data = options.data;
observer(this._data, options.render);
let watcher = new Watcher(this, );
}
}
function defineReactive (obj, key, val, cb) {
/*在闭包内存储一个Dep对象*/
const dep = new Dep();
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get: ()=>{
if (Dep.target) {
/*Watcher对象存在全局的Dep.target中*/
dep.addSub(Dep.target);
}
},
set:newVal=> {
/*只有之前addSub中的函数才会触发*/
dep.notify();
}
})
}
Dep.target = null; //防止依赖重复添加这儿我们通过示例来讲解
{{a+b}}
{{a-c}}
基本
文件
流程
错误
SQL
调试
- 请求信息 : 2026-06-06 23:34:28 HTTP/1.1 GET : /article/gpesdp.html
- 运行时间 : 1.6173s ( Load:0.0082s Init:1.0053s Exec:0.5947s Template:0.0090s )
- 吞吐率 : 0.62req/s
- 内存开销 : 2,237.76 kb
- 查询信息 : 12 queries 5 writes
- 文件加载 : 36
- 缓存信息 : 0 gets 0 writes
- 配置加载 : 130
- 会话信息 : SESSION_ID=3hcs8f4vtpk0mhrqsufccr0bg7
- /www/wwwroot/tsicrk.com/index.php ( 1.09 KB )
- /www/wwwroot/tsicrk.com/ThinkPHP/ThinkPHP.php ( 4.61 KB )
- /www/wwwroot/tsicrk.com/ThinkPHP/Library/Think/Think.class.php ( 12.26 KB )
- /www/wwwroot/tsicrk.com/ThinkPHP/Library/Think/Storage.class.php ( 1.37 KB )
- /www/wwwroot/tsicrk.com/ThinkPHP/Library/Think/Storage/Driver/File.class.php ( 3.52 KB )
- /www/wwwroot/tsicrk.com/ThinkPHP/Mode/common.php ( 2.82 KB )
- /www/wwwroot/tsicrk.com/ThinkPHP/Common/functions.php ( 53.56 KB )
- /www/wwwroot/tsicrk.com/ThinkPHP/Library/Think/Hook.class.php ( 4.01 KB )
- /www/wwwroot/tsicrk.com/ThinkPHP/Library/Think/App.class.php ( 13.49 KB )
- /www/wwwroot/tsicrk.com/ThinkPHP/Library/Think/Dispatcher.class.php ( 14.79 KB )
- /www/wwwroot/tsicrk.com/ThinkPHP/Library/Think/Route.class.php ( 13.36 KB )
- /www/wwwroot/tsicrk.com/ThinkPHP/Library/Think/Controller.class.php ( 11.23 KB )
- /www/wwwroot/tsicrk.com/ThinkPHP/Library/Think/View.class.php ( 7.59 KB )
- /www/wwwroot/tsicrk.com/ThinkPHP/Library/Behavior/BuildLiteBehavior.class.php ( 3.68 KB )
- /www/wwwroot/tsicrk.com/ThinkPHP/Library/Behavior/ParseTemplateBehavior.class.php ( 3.88 KB )
- /www/wwwroot/tsicrk.com/ThinkPHP/Library/Behavior/ContentReplaceBehavior.class.php ( 1.91 KB )
- /www/wwwroot/tsicrk.com/ThinkPHP/Conf/convention.php ( 11.15 KB )
- /www/wwwroot/tsicrk.com/App/Common/Conf/config.php ( 2.14 KB )
- /www/wwwroot/tsicrk.com/ThinkPHP/Lang/zh-cn.php ( 2.55 KB )
- /www/wwwroot/tsicrk.com/ThinkPHP/Conf/debug.php ( 1.49 KB )
- /www/wwwroot/tsicrk.com/App/Home/Conf/config.php ( 0.31 KB )
- /www/wwwroot/tsicrk.com/App/Home/Common/function.php ( 3.33 KB )
- /www/wwwroot/tsicrk.com/ThinkPHP/Library/Behavior/ReadHtmlCacheBehavior.class.php ( 5.62 KB )
- /www/wwwroot/tsicrk.com/App/Home/Controller/ArticleController.class.php ( 6.02 KB )
- /www/wwwroot/tsicrk.com/App/Home/Controller/CommController.class.php ( 1.60 KB )
- /www/wwwroot/tsicrk.com/ThinkPHP/Library/Think/Model.class.php ( 60.11 KB )
- /www/wwwroot/tsicrk.com/ThinkPHP/Library/Think/Db.class.php ( 32.43 KB )
- /www/wwwroot/tsicrk.com/ThinkPHP/Library/Think/Db/Driver/Pdo.class.php ( 16.74 KB )
- /www/wwwroot/tsicrk.com/ThinkPHP/Library/Think/Cache.class.php ( 3.83 KB )
- /www/wwwroot/tsicrk.com/ThinkPHP/Library/Think/Cache/Driver/File.class.php ( 5.87 KB )
- /www/wwwroot/tsicrk.com/ThinkPHP/Library/Think/Template.class.php ( 28.16 KB )
- /www/wwwroot/tsicrk.com/ThinkPHP/Library/Think/Template/TagLib/Cx.class.php ( 22.40 KB )
- /www/wwwroot/tsicrk.com/ThinkPHP/Library/Think/Template/TagLib.class.php ( 9.16 KB )
- /www/wwwroot/tsicrk.com/App/Runtime/Cache/Home/7540f392f42b28b481b30614275e4e55.php ( 17.71 KB )
- /www/wwwroot/tsicrk.com/ThinkPHP/Library/Behavior/WriteHtmlCacheBehavior.class.php ( 0.97 KB )
- /www/wwwroot/tsicrk.com/ThinkPHP/Library/Behavior/ShowPageTraceBehavior.class.php ( 5.24 KB )
- [ app_init ] --START--
- Run Behavior\BuildLiteBehavior [ RunTime:0.000006s ]
- [ app_init ] --END-- [ RunTime:0.000032s ]
- [ app_begin ] --START--
- Run Behavior\ReadHtmlCacheBehavior [ RunTime:0.000382s ]
- [ app_begin ] --END-- [ RunTime:0.000408s ]
- [ view_parse ] --START--
- [ template_filter ] --START--
- Run Behavior\ContentReplaceBehavior [ RunTime:0.000055s ]
- [ template_filter ] --END-- [ RunTime:0.000077s ]
- Run Behavior\ParseTemplateBehavior [ RunTime:0.006190s ]
- [ view_parse ] --END-- [ RunTime:0.006215s ]
- [ view_filter ] --START--
- Run Behavior\WriteHtmlCacheBehavior [ RunTime:0.000156s ]
- [ view_filter ] --END-- [ RunTime:0.000170s ]
- [ app_end ] --START--
- 1064:You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') LIMIT 1' at line 1
[ SQL语句 ] : SELECT `id`,`pid`,`navname` FROM `cx_nav` WHERE ( id= ) LIMIT 1
- 1064:You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') LIMIT 1' at line 1
[ SQL语句 ] : SELECT `id`,`navname` FROM `cx_nav` WHERE ( id= ) LIMIT 1
- 1064:You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 1
[ SQL语句 ] : SELECT `id`,`navname` FROM `cx_nav` WHERE ( pid= )
- [8] Undefined index: pid /www/wwwroot/tsicrk.com/App/Home/Controller/ArticleController.class.php 第 47 行.
- [8] Undefined index: db_host /www/wwwroot/tsicrk.com/ThinkPHP/Library/Think/Db.class.php 第 120 行.
- [8] Undefined index: db_port /www/wwwroot/tsicrk.com/ThinkPHP/Library/Think/Db.class.php 第 121 行.
- [8] Undefined index: db_name /www/wwwroot/tsicrk.com/ThinkPHP/Library/Think/Db.class.php 第 122 行.

1.6173s
