实现之前我们得先看一下Object.defineProperty的实现,因为vue主要是通过数据劫持来实现的,通过get、set来完成数据的读取和更新。
var obj={name:'wclimb'} var age=24 Object.defineProperty(obj,'age',{ enumerable: true, // 可枚举 configurable: false, // 不能再define get () { return age }, set (newVal) { console.log('我改变了',age +' -> '+newVal); age=newVal } }) > obj.age > 24 > obj.age=25; > 我改变了 24 -> 25 > 25
从上面可以看到通过get获取数据,通过set监听到数据变化执行相应操作,还是不明白的话可以去看看Object.defineProperty文档。
<div id="wrap"> <p v-html="test"></p> <input type="text" v-model="form"> <input type="text" v-model="form"> <button @click="changeValue">改变值</button> {{form}} </div>
new Vue({ el: '#wrap', data:{ form: '这是form的值', test: '<strong>我是粗体</strong>', }, methods:{ changeValue(){ console.log(this.form) this.form='值被我改变了,气不气?' } } })
class Vue{ constructor(){} proxyData(){} observer(){} compile(){} compileText(){} } class Watcher{ constructor(){} update(){} }
class Vue{ constructor(options={}){ this.$el=document.querySelector(options.el); let data=this.data=options.data; // 代理data,使其能直接this.xxx的方式访问data,正常的话需要this.data.xxx Object.keys(data).forEach((key)=> { this.proxyData(key); }); this.methods=obj.methods // 事件方法 this.watcherTask={}; // 需要监听的任务列表 this.observer(data); // 初始化劫持监听所有数据 this.compile(this.$el); // 解析dom } }
上面主要是初始化操作,针对传过来的数据进行处理
class Vue{ constructor(options={}){ ...... } proxyData(key){ let that=this; Object.defineProperty(that, key, { configurable: false, enumerable: true, get () { return that.data[key]; }, set (newVal) { that.data[key]=newVal; } }); } }
上面主要是代理data到最上层,this.xxx的方式直接访问data
class Vue{ constructor(options={}){ ...... } proxyData(key){ ...... } observer(data){ let that=this Object.keys(data).forEach(key=>{ let value=data[key] this.watcherTask[key]=[] Object.defineProperty(data,key,{ configurable: false, enumerable: true, get(){ return value }, set(newValue){ if(newValue !==value){ value=newValue that.watcherTask[key].forEach(task=> { task.update() }) } } }) }) } }
同样是使用Object.defineProperty来监听数据,初始化需要订阅的数据。
把需要订阅的数据到push到watcherTask里,等到时候需要更新的时候就可以批量更新数据了。??下面就是;
遍历订阅池,批量更新视图。
set(newValue){ if(newValue !==value){ value=newValue // 批量更新视图 that.watcherTask[key].forEach(task=> { task.update() }) } } compile 解析dom class Vue{ constructor(options={}){ ...... } proxyData(key){ ...... } observer(data){ ...... } compile(el){ var nodes=el.childNodes; for (let i=0; i < nodes.length; i++) { const node=nodes[i]; if(node.nodeType===3){ var text=node.textContent.trim(); if (!text) continue; this.compileText(node,'textContent') }else if(node.nodeType===1){ if(node.childNodes.length > 0){ this.compile(node) } if(node.hasAttribute('v-model') && (node.tagName==='INPUT' || node.tagName==='TEXTAREA')){ node.addEventListener('input',(()=>{ let attrVal=node.getAttribute('v-model') this.watcherTask[attrVal].push(new Watcher(node,this,attrVal,'value')) node.removeAttribute('v-model') return ()=> { this.data[attrVal]=node.value } })()) } if(node.hasAttribute('v-html')){ let attrVal=node.getAttribute('v-html'); this.watcherTask[attrVal].push(new Watcher(node,this,attrVal,'innerHTML')) node.removeAttribute('v-html') } this.compileText(node,'innerHTML') if(node.hasAttribute('@click')){ let attrVal=node.getAttribute('@click') node.removeAttribute('@click') node.addEventListener('click',e=> { this.methods[attrVal] && this.methods[attrVal].bind(this)() }) } } } }, compileText(node,type){ let reg=/\{\{(.*)\}\}/g, txt=node.textContent; if(reg.test(txt)){ node.textContent=txt.replace(reg,(matched,value)=>{ let tpl=this.watcherTask[value] || [] tpl.push(new Watcher(node,this,value,type)) return value.split('.').reduce((val, key)=> { return this.data[key]; }, this.$el); }) } } }
这里代码比较多,我们拆分看你就会觉得很简单了
首先我们先遍历el元素下面的所有子节点,node.nodeType===3 的意思是当前元素是文本节点,node.nodeType===1 的意思是当前元素是元素节点。因为可能有的是纯文本的形式,如纯双花括号就是纯文本的文本节点,然后通过判断元素节点是否还存在子节点,如果有的话就递归调用compile方法。下面重头戏来了,我们拆开看:
if(node.hasAttribute('v-html')){ let attrVal=node.getAttribute('v-html'); this.watcherTask[attrVal].push(new Watcher(node,this,attrVal,'innerHTML')) node.removeAttribute('v-html') }
上面这个首先判断node节点上是否有v-html这种指令,如果存在的话,我们就发布订阅,怎么发布订阅呢?只需要把当前需要订阅的数据push到watcherTask里面,然后到时候在设置值的时候就可以批量更新了,实现双向数据绑定,也就是下面的操作
that.watcherTask[key].forEach(task=> { task.update() })
然后push的值是一个Watcher的实例,首先他new的时候会先执行一次,执行的操作就是去把纯双花括号 -> 1,也就是说把我们写好的模板数据更新到模板视图上。
最后把当前元素属性剔除出去,我们用Vue的时候也是看不到这种指令的,不剔除也不影响
至于Watcher是什么,看下面就知道了
that.watcherTask[key].forEach(task=> { task.update() })
之前发布订阅之后走了这里面的操作,意思就是把当前元素如:node.innerHTML='这是data里面的值'、node.value='这个是表单的数据'
那么我们为什么不直接去更新呢,还需要update做什么,不是多此一举吗?
其实update记得吗?我们在订阅池里面需要批量更新,就是通过调用Watcher原型上的update方法。
写在最后:欢迎留言讨论,关于Java架构进阶私信“Java”或“架构资料”有惊喜!加关注,持续更新!
ue的使用相信大家都很熟练了,使用起来简单。但是大部分人不知道其内部的原理是怎么样的,今天我们就来一起实现一个简单的vue。实现之前我们得先看一下Object.defineProperty()的实现,因为vue主要是通过数据劫持来实现的,通过get、set来完成数据的读取和更新。
从上面可以看到通过get获取数据,通过set监听到数据变化执行相应操作,还是不明白的话可以去看看Object.defineProperty文档。
流程图
html代码结构
js调用
Vue结构
Vue constructor 初始化
proxyData 代理data
observer 劫持监听
同样是使用Object.defineProperty来监听数据,初始化需要订阅的数据。把需要订阅的数据到push到watcherTask里,等到时候需要更新的时候就可以批量更新数据了。
uePress 是一个以 Markdown 为中心的静态网站生成器。你可以使用 Markdown 来书写内容(如文档、博客等),然后 VuePress 会帮助你生成一个静态网站来展示它们。
VuePress 诞生的初衷是为了支持 Vue.js 及其子项目的文档需求,但是现在它已经在帮助大量用户构建他们的文档、博客和其他静态网站。
首先,安装 VuePress 最新版本及相关依赖:
# 安装 VuePress
npm install -D vuepress@next
# 安装 Vite 打包工具和默认主题
npm install -D @vuepress/bundler-vite@next @vuepress/theme-default@next
以下是安装过程中的示例输出:
virhuiai@virhuiaideMBP vite-project % npm install -D vuepress@next
(#########?????????) ? idealTree:vite-project: timing idealTree:#root Completed in 16997ms
added 112 packages, audited 158 packages in 2m
31 packages are looking for funding
run `npm fund` for details
found 0 vulnerabilities
virhuiai@virhuiaideMBP vite-project %
virhuiai@virhuiaideMBP vite-project % npm install -D @vuepress/bundler-vite@next @vuepress/theme-default@next
added 79 packages, audited 237 packages in 1m
63 packages are looking for funding
run `npm fund` for details
found 0 vulnerabilities
创建必要的目录和配置文件:
# 创建文档目录和配置目录
mkdir docs
mkdir docs/.vuepress
创建 VuePress 配置文件:
# docs/.vuepress/config.js
import { viteBundler } from '@vuepress/bundler-vite'
import { defaultTheme } from '@vuepress/theme-default'
import { defineUserConfig } from 'vuepress'
export default defineUserConfig({
bundler: viteBundler(),
theme: defaultTheme(),
})
创建你的第一篇文档:
echo '# Hello VuePress' > docs/README.md
项目目录结构如下:
├─ docs
│ ├─ .vuepress
│ │ └─ config.js
│ └─ README.md
└─ package.json
建议的 .gitignore 配置如下:
# 忽略 VuePress 生成的临时文件和缓存
.vuepress/.temp
.vuepress/.cache
.vuepress/dist
在 package.json 中配置启动和构建脚本:
{
"scripts": {
"docs:dev": "vuepress dev docs",
"docs:build": "vuepress build docs"
}
}
启动开发服务器:
npm run docs:dev
构建静态网站:
npm run docs:build
安装 ElementPlus:
npm i element-plus -S
配置VuePress以使用ElementPlus:
# docs/.vuepress/client.js
import { defineClientConfig } from 'vuepress/client'
import ElementPlus from 'element-plus';
import 'element-plus/dist/index.css'
export default defineClientConfig({
enhance({ app, router, siteData }) {
app.use(ElementPlus);
},
setup() {},
rootComponents: [],
})
在 Markdown 文件中使用 ElementPlus 组件:
<el-button type="primary">Primary</el-button>
<el-button type="success">Success</el-button>
<el-button type="info">Info</el-button>
<el-button type="warning">Warning</el-button>
<el-button type="danger">Danger</el-button>
重新启动开发服务器查看效果:
*请认真填写需求信息,我们会在24小时内与您取得联系。