当前位置:网站首页>The native API of the future trend of the front end: web components
The native API of the future trend of the front end: web components
2020-11-06 21:07:00 【itread01】
[ Original code interpretation ](https://github.com/yyx990803/vue-lit/blob/master/index.js) ```js // lit-html Templates , Provide html Templates ( Simple js Expression and event binding )、render Rendering capabilities import { render } from 'https://unpkg.com/lit-html?module' // reactivity yes vue3.0 At the heart of ,shallowReactive Shallow response ,effect It can be understood as watch, Provide attribute response and partial lifecycle processing import { shallowReactive, effect } from 'https://unpkg.com/@vue/reactivity/dist/reactivity.esm-browser.js' let currentInstance export function defineComponent(name, propDefs, factory) { if (typeof propDefs === 'function') { factory = propDefs propDefs = [] } // Custom elements custom element, Native API customElements.define( name, class extends HTMLElement { // Set the properties you want to listen to static get observedAttributes() { return propDefs } constructor() { super() // Attribute access vue In response to const props = (this._props = shallowReactive({})) currentInstance = this // lit-html Of html Generated templates const template = factory.call(this, props) currentInstance = null // bm onBeforeMount this._bm && this._bm.forEach((cb) => cb()) // shadowRoot,closed You can't go directly through js Get the defined customElement operation shadowRoot const root = this.attachShadow({ mode: 'closed' }) let isMounted = false effect(() => { if (isMounted) { // _bu, onBeforeUpdate this._bu && this._bu.forEach((cb) => cb()) } // Will template Mount the content to shadowRoot On render(template(), root) if (isMounted) { // _u,onUpdated this._u && this._u.forEach((cb) => cb()) } else { isMounted = true } }) } // Mount to for the first time dom Call back later ,onMounted connectedCallback() { this._m && this._m.forEach((cb) => cb()) } // Uninstall , onUnmounted disconnectedCallback() { this._um && this._um.forEach((cb) => cb()) } // Attribute listening attributeChangedCallback(name, oldValue, newValue) { this._props[name] = newValue } } ) } function createLifecycleMethod(name) { return (cb) => { if (currentInstance) { ;(currentInstance[name] || (currentInstance[name] = [])).push(cb) } } } export const onBeforeMount = createLifecycleMethod('_bm') export const onMounted = createLifecycleMethod('_m') export const onBeforeUpdate = createLifecycleMethod('_bu') export const onUpdated = createLifecycleMethod('_u') export const onUnmounted = createLifecycleMethod('_um') export * from 'https://unpkg.com/lit-html?module' export * from 'https://unpkg.com/@vue/reactivity/dist/reactivity.esm-browser.js' ``` [shallowReactive Source code ](https://github.com/vuejs/vue-next/blob/master/packages/reactivity/src/reactive.ts), Function annotations have made it clear ,only the root level properties are reactive. The object only responds to the root attribute , In other words , Shallow response , It's similar to a shallow copy . ```js /** * Return a shallowly-reactive copy of the original object, where only the root * level properties are reactive. It also does not auto-unwrap refs (even at the * root level). */ export function shallowReactive
#### input、select And so on html Elements input、select It's also web component. But it's built-in , Default can't see shadowRoot Structure , Need to open browser console settings , Tick `Show user agent shadow DOM`, In the console `elements` We can see its structure in . Set
dom Structure
## web components Componentization by 3 Part of it . - **Custom elements( Custom elements )**: A set of JavaScript API, Allows you to define custom elements And their behavior , You can then use them as needed in your user interface . - **Shadow DOM( shadow DOM)**: A set of JavaScript API, Used to encapsulate “ shadow ”DOM Trees are attached to elements ( With the master file DOM Present separately ) And control its associated functions . In this way , You can keep the functionality of the element private , So they can be scripted and stylized , And don't worry about conflict with the rest of the file . - **HTML templates(HTML Templates )**: `
` and `
It can be as common as the operation DOM The same thing , utilize API operation Shoadow DOM. ```js let shadow = elementRef.attachShadow({mode: 'open'}); let shadow = elementRef.attachShadow({mode: 'closed'}); ``` `open` It means that you can use the JavaScript Method to get Shadow DOM, Such as 'document.querySelector('custom-info').shadowRoot'. conversely , Can't get . more , Please refer to :[Shadow DOM](https://developer.mozilla.org/zh-CN/docs/Web/Web_Components/Using_shadow_DOM) ### HTML templates template and slot Elements can create very flexible shadow DOM Templates , To fill custom element. For repeated use html Structure , It can simplify things , It's very meaningful . Example ```html
[ Other libraries todolist parade ](https://wc-todo.firebaseapp.com/)
Look at the picture , The result is self-evident . ## Summary Browser native capabilities are becoming very powerful .web component It's worth a hug . Although template It's not perfect ( Expressions are not supported ), But it's just a black spot on the whiteboard . Refer to : 1. [ Especially large 3 It was sent on GitHub Upper vue-lit What is it ?](https://github.com/axuebin/articles/issues/41) 2. [Web Components](https://developer.mozilla.org/zh-CN/docs/Web/Web_Components) 3. [web-components-todo](https://github.com/shprink/web-component
版权声明
本文为[itread01]所创,转载请带上原文链接,感谢
边栏推荐
- Isn't data product just a report? absolutely wrong! There are university questions in this category
- Introduction to the structure of PDF417 bar code system
- An article taught you to download cool dog music using Python web crawler
- Summary of front-end performance optimization that every front-end engineer should understand:
- nacos、ribbon和feign的簡明教程
- 【学习】接口测试用例编写和测试关注点
- StickEngine-架构11-消息队列(MessageQueue)
- Behind the first lane level navigation in the industry
- What are the common problems of DTU connection
- 解决 WPF 绑定集合后数据变动界面却不更新的问题
猜你喜欢

ES6 learning notes (2): teach you to play with class inheritance and class objects

Python basic variable type -- list analysis

大数据处理黑科技:揭秘PB级数仓GaussDB(DWS) 并行计算技术

2020-09-09:裸写算法:两个线程轮流打印数字1-100。

A small goal in 2019 to become a blog expert of CSDN

To Lianyun analysis: why is IPFs / filecoin mining so difficult?

2020-09-04:函数调用约定了解么?

The AI method put forward by China has more and more influence. Tianda et al. Mined the development law of AI from a large number of literatures

华为Mate 40 系列搭载HMS有什么亮点?

An article takes you to understand CSS gradient knowledge
随机推荐
Zero basis to build a web search engine of its own
Kubernetes and OAM to build a unified, standardized application management platform knowledge! (Internet disk link attached)
常用SQL语句总结
Even liver three all night, jvm77 high frequency interview questions detailed analysis, this?
Metersphere developer's Manual
Digital city responds to relevant national policies and vigorously develops the construction of digital twin platform
StickEngine-架构12-通信协议
Live broadcast preview | micro service architecture Learning Series live broadcast phase 3
Use modelarts quickly, zero base white can also play AI!
华为Mate 40 系列搭载HMS有什么亮点?
It's time for your financial report to change to a more advanced style -- financial analysis cockpit
【转发】查看lua中userdata的方法
ES6 learning notes (4): easy to understand the new grammar of ES6
美团内部讲座|周烜:华东师范大学的数据库系统研究
Elasticsearch database | elasticsearch-7.5.0 application construction
大会倒计时|2020 PostgreSQL亚洲大会-中文分论坛议程安排
事务的隔离级别与所带来的问题
Description of phpshe SMS plug-in
Zero basis to build a web search engine of its own
Will blockchain be the antidote to the global epidemic accelerating the transformation of Internet enterprises?