当前位置:网站首页>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]所创,转载请带上原文链接,感谢
边栏推荐
- Outsourcing is really difficult. As an outsourcer, I can't help sighing.
- Network programming NiO: Bio and NiO
- 华为Mate 40 系列搭载HMS有什么亮点?
- Vue communication and cross component listening state Vue communication
- ado.net和asp.net的关系
- html+vue.js 實現分頁可相容IE
- What is the meaning of sector sealing of filecoin mining machine since the main network of filecoin was put online
- Summary of front-end performance optimization that every front-end engineer should understand:
- CloudQuery V1.2.0 版本发布
- Python basic data type -- tuple analysis
猜你喜欢

Even liver three all night, jvm77 high frequency interview questions detailed analysis, this?

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

GUI engine evaluation index

Some operations kept in mind by the front end foundation GitHub warehouse management

An article takes you to understand CSS gradient knowledge

Axios learning notes (2): easy to understand the use of XHR and how to package simple Axios

ES6 learning notes (4): easy to understand the new grammar of ES6

ES6 learning notes (3): teach you to use js object-oriented thinking to realize the function of adding, deleting, modifying and checking tab column

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

行为型模式之解释器模式
随机推荐
ES6 learning notes (5): easy to understand ES6's built-in extension objects
An article taught you to download cool dog music using Python web crawler
python100例項
What knowledge do Python automated testing learn?
【ElasticSearch搜索引擎】
行为型模式之备忘录模式
The method of realizing high SLO on large scale kubernetes cluster
How to understand Python iterators and generators?
Application of restful API based on MVC
To teach you to easily understand the basic usage of Vue codemirror: mainly to achieve code editing, verification prompt, code formatting
Details of dapr implementing distributed stateful service
Why is quicksort so fast?
Introduction to Google software testing
ado.net和asp.net的关系
Ronglian completed US $125 million f round financing
事务的本质和死锁的原理
An article will take you to understand CSS alignment
2020年数据库技术大会助力技术提升
Behind the first lane level navigation in the industry
What is the meaning of sector sealing of filecoin mining machine since the main network of filecoin was put online