This is the 13th day of my participation in the August More Text Challenge.More challenges in August

Weex basic development guide to bring you ~ the relevant knowledge points in this article are before xiaobian in learning Weex in a little bit of ji Lei down, Weex related development documents are very few, I hope to help you develop.

This article is best read after viewing the Weex official documents.

More articles on my github and personal public account [quan Zhandao Road], welcome to watch [front-end knowledge], if you benefit, no money, little hands dot a Star

Read this article and you will learn

  • Weex differentiation
  • How to start development with Weex
  • Syntax differences in Weex

differentiation

Platform differences between Weex and traditional Web

  • Weex is a cross-platform solution, and the Web is only used as a development environment
  • Weex does not existDOM
    • There is noElement , EventObjects such as
    • There are only limited event types andnativeCommon event types, such asLongpress.AppearEtc.
  • There is no BOM for Weex
    • There is nodocument , windowObjects such as
    • Provides its own object to obtain partial device dataWXEnvironment
  • The Weex operating environment is mainly native applicationsAndroidiOSNative components are rendered in the environment instead ofDOMElements.
  • Weex provides a native device call API
    • Clipboard
    • Navigator Navigation Control
    • Storage Local Storage

Differences between WeeX-Toolkit and Weexpack

  • weex-toolkitInitializing the project is directed at developing a singleWeexPage by page, that is, such a project only includes things needed for a single page development, such as front-end page source files,webpackConfiguration,npmScript, etc. The output generated by the project is oneJS BundleFiles can be deployed freely.
  • weexpackIs to initialize a complete App project, includingAndroidiOSThe entireAppTo start, the front-end page is only part of it. The final output of such a project is oneAndroid AppAnd aiOS App.

A necessary condition for

  • The development environment
    • nodeJS
    • Android Development Environment
    • IOS Development Environment
  • The development tools
    • Sublime Text
    • Android studio
    • Xcode
  • Code management
    • Github

Quick start

Install the relevant development environment

  • Install the Node development environment
  • Install the Android & IOS development environment

Install weex – cli

  • npm install weex-toolkit -g

Create a project using the WEEx CLI

  • weex create demo-project
  • Enter related configuration information

Download project dependency packages

  • After entering the projectnpm install

Preview the project

Browser preview

  • npm start
  • After executing the command, the page window of the browser will be automatically opened. However, it is recommended to use the real computer for preview. Some styles and codes on the Web end differ greatly from those on the Native end

Native client preview

  • Compile to JS Bundle files
    • Weex compile < source directory or file >
  • Compression compilation
    • Weex compile < source directory or file > < package directory or file > -m
  • Configure Nginx
  • Mobile application client access

The development of

Operation process

  • Write Vue code locally to generate Web pages
  • Weex formJS bundle
  • In the cloud, the network request or pre-delivery will beJS bundleTo the user’s mobile application client
  • In the mobile application client,WeexSDKOne will be readyJavaScriptEngine, and executes when the user opens a Weex pageJS bundle
  • Various commands are sent tonativeTerminal interface rendering or data storage, network communication, call device functions, user interaction response

File structure

  • | – SRC / / source directory
  • | – node_modules / / rely on the package
  • | – dist / / deposit compiled js files
  • | – build/store/NPM build js file, can be in the package. The json file configuration
  • | – package. Json / / project configuration and rely on libraries
  • | – webpack. Config. Js / / webpack packaging configuration file
  • | – config. Js / / projects related to the configuration file, you can be in this file switch configured in different environments

Navigation way

Vue-Router

  • With the Vue

weex-navigator

  • Borrow the IOS/Android Navigator module

  • use

    • Push a WEEX page URL onto the navigation stack
    Push ({url :"" // The URL of the Weex page to be pressed into; animated:"" // "true" indicates that the page is animated, "false" does not, the default is "true". }, callback(){// callback()});Copy the code
    • Pop the current Weex page onto the navigation stack
    Pop ({animated:"" // "true" indicates that page loading requires animation, "false" does not, default is "true". }, callback(){// callback()});Copy the code

The data transfer

The way the Vue

  • props
  • this.$emit('fun', data)

storage

  • Permanent, in the H5/ Web side is actually usedHTML5 LocalStorage API
  • Limitations:
    • The maximum size of the H5 or web terminal is 5M
    • There are no restrictions on Android and IOS
  • The relevant API
    • setItem(key, value, callback)
    • getItem(key, callback)
    • removeItem(key, callback)
    • length(callback)
    • getAllKeys(callback)

Address together

  • usingweex.config.bundleUrl
  • use
/ / routing way to carry the navigator. Push ({url: "http://192.168.xxx.xxx:8081/tmp/detail.js? Id =1', animated: 'true'}) getUrlParam() {let name, value; let str = weex.config.bundleUrl; Let num = str.indexof ("?") ); str = str.substr(num + 1); Let arr = str.split("&"); For (var I = 0; i < arr.length; i++) { num = arr[i].indexOf("="); if (num > 0) { name = arr[i].substring(0, num); value = arr[i].substr(num + 1); this.paramsDic[name] = value; }}}Copy the code

BroadcastChannel

  • The source code to define
Declare Interface BroadcastChannel = {name: string, // Channel name postMessage: (message: any) => void; Onmessage: (event: MessageEvent) => void; Close: () => void; // Close communication}Copy the code
  • Communication process

  • use
// Broadcast const broadcast = new BroadcastChannel('testChannel') broadcast.postMessage('this is amessage.') modal.toast({ message: Let self = this const broadcast = new BroadcastChannel('testChannel') broadcast.onMessage = Function (event) {modal.toast({message: 'message received'}) self.testData = event.data}Copy the code

Borrow native for transit bridge

  • vue -> native -> vue

Data communication Stream module

Request process

  • When the WEEX sends a FETCH request, it passes through the Native stream module first, and the Stream module sends the request to the server.

The request instancefetch(options, callback, progressCallback)

  • @optionsThe requested configuration options support the following configurations
    • method: string, the HTTP request method, value of GET/POST/PUT/DELETE/PATCH/HEAD
    • url: string, the requested URL | string
    • headers: string, HTTP request header
    • type: string, response type: JSON, text or jSONp
    • body: string indicates the HTTP request Body. Only string data is supported. JSON is not supported'param1=p1&param2=p2'
  • The defaultContent-Typeapplication/x-www-form-urlencoded
  • @callbackThe callback function will receive the following response object:
    • status: number, the returned status code
    • ok: Boolean, true if the status code is between 200-299
    • statusText: string, status description text
    • dataIf the request type is JSON or JSONp, it is an object, otherwise it is a string.
    • headers: object: HTTP response header
  • @progressCallback, function, request progress in the request process.
    • readyState: number, current status, 1: the connection is being requested. 2: returns to the response header. 3: Returned data is being loaded
    • status: number, the returned status code
    • length: number: indicates the received data length. You can get the total length from the response header
    • statusText: string, status description text
    • headers: object: HTTP response header

Use the sample

  • GET
let self = this stream.fetch({ method: 'GET', url: GET_URL, type:'json' }, function(req) { if(! req.ok){ self.getResult = "request failed"; }else{ console.log('get:'+req); self.getResult = JSON.stringify(req.data); } },function(response){ console.log('get in progress:'+response.length); self.getResult = "bytes received:"+response.length; });Copy the code
  • POST
let self = this stream.fetch({ method: 'POST', url: POST_URL, type:'json', body: stringData }, function(req) { if(! req.ok){ self.postResult = "request failed"; }else{ console.log('get:'+JSON.stringify(req)); self.postResult = JSON.stringify(req.data); } },function(response){ console.log('get in progress:'+response.length); self.postResult = "bytes received:"+response.length; });Copy the code

Syntax differences

HTML tags

  • Note Following the weeX official documents, some label styles are not guaranteed to work properly on weeX machines
    • Such as<span>
  • The WEEX label is parsed into different labels
    • <text> -> <p>
  • Structure does not support improper nesting
    • Such as:<text>nested<text>
  • <div>The WEEX is not scrollable. You need to use scroll labels<list>or<scroller>or<waterfall>
  • Partially detailed constraints
    • <a>Do not add text directly<text>To display the text
    • <input>Disable to setdisabled=trueCan’t abbreviations
    • <input>Two different propertiesmaxlengthNumeric typesmax-lengthIf you enter a string, the test fails and counts as input, not bytes
    • <div>CSS and bidirectional binding will not work if you add text directly inside
    • <web>Used to embed a web page content in weeX pages, and HTML<iframe>The effect is similar.

CSS styles

  • supportpxwxThe length of the unit
  • Support inline styles andThe class name of the classCannot be setId name, the real machine failed
  • Style inheritance is not supported
  • Inline styles are not supportedflexLayout to solve
  • Unsupported hierarchyz-indexThe hierarchy overlay is shown in writing order
  • Does not supportbox-shadow
  • CSS triangles are not supported
  • Style abbreviations are not supported
  • Partial support for pseudo-class styles
    • Weex supports four pseudo-classes:active.focus.disabled.enabled
    • All components are supportedactive
    • only<input>The component and<textarea>Components supportfocus , enabled.diabled
  • The space and carriage return problems in standard CSS also exist on real computers
  • Partial detail constraint
    • <textarea>Rows must be set, which defaults to 2, otherwise only two rows will be displayed
    • <textarea>attributeplaceholder-colorSet the placeholder color
    • <image>The width and height properties must be set to display
    • <image>Width Full 750px;
    • <image>Fill up according to the ratio of width to heightflex:1;
    • <list><scroller>Nested lists or scrollbars in the same direction are not supported
    • <text>CSS styleslines:1;Setting beyond hide shows ellipsis partially invalid
    • positionThe new attributestikyFixed header for scrolling

JavaScript

  • Weex is not supportedPromisefinally()Methods, supportthen()catch()
  • v-ifsupportv-showDoes not support
  • The bubbling mechanism
    • Note The bubbling mechanism in the WEEX is disabled by defaultbubble = true
    • To prevent a bubbleevent.stopPropagation();
  • Support gesture operation listening

Write in the last

If you find this article beneficial to you, please like it and share it with more people who need it!

Welcome to pay attention to “Quanzhandao road” and wechat official account “Quanzhandao Road”, get more good articles and free books!
If you need [Baidu] & [Bytedance] & [JINGdong] & [Ape Tutoring], please leave a message, you will enjoy VIP speed push service ~

Past oliver

Implementation of wechat JS API payment

Create a personalized Github profile

The interviewer asks you<img>What would you say about the element

Special JS floating-point number storage and calculation

Long [word] baidu and good interview after containing the answer | the nuggets technology essay in the future

Front end practical regular expression & tips, all throw you 🏆 nuggets all technical essay | double festival special articles

A detailed explanation of the unpopular HTML tabIndex

A few lines of code teach you to solve the wechat generated posters and two-dimensional code

Principle of Vue3.0 Responsive data: ES6 Proxy

Make the interviewer fall in love with you

How to draw a fine line gracefully

[3 minutes] Front-end performance optimization -HTML, CSS, JS parts

Front-end performance Optimization – Page loading speed optimization

Front-end Performance Optimization – Network transport layer optimization