background

WeChat applet, released from the earliest to pay treasure to small procedures, small nailing, byte to beat small program, a small program that baidu, QQ small programs, etc., in the face of so many sets of code, developers to write more than native code obviously is very high, the cost of using words of H5 experience and not as good as native, this time only need to write a set of code, The ability to adapt to multiple aspects is particularly needed. Let’s get down to business and introduce the development of uni-app byte applets

Preparatory work

  • The default headline applet APPID has been applied successfully
  • Install development tools baidu small program developer tools Bytedance developer tools HBuilderX or other your favorite IDE can

Project development

New project

This can be done through the HBuilderX visual interface and vue-CLI command line. The following describes how to create a new project using vue-CLI command line

  • Global installation vUE – CLI
npm install -g @vue/cli
Copy the code
  • create
vue create -p dcloudio/uni-preset-vue user-uni-order
Copy the code

After the installation is successful, you will be prompted to select a template. We will choose the default template

Overall project process

Order -> Order Status -> Complete payment, as follows:

Develop a directory structure

┌ ─ components / / uni - app directory components │ └ ─ comp - Dr. Ue / / reusable components a ├ ─ common / / general js&css tool ├ ─ hybrid/store/local web directory ├ ─ platforms / / for each platform dedicated page directory ├ ─ pages / / business page file storage directory │ ├ ─ index │ │ └ ─ components / / page level component │ │ └ ─ vuex / / deposit vuex main index index page logic │ │ └ ─ index. Vue / / index page ├ ─ static / / storage application reference static resources (such as images, video, etc.) │ ├ ─ mp - weixin / / conditional compilation PNG │ │ └ ─ Amy polumbo ng │ │ └ ─ p. ng ├ ─ store / / state unified management, ├─service // Add up the vuex exercises for each page API such as │ └ ─ API. Js/API/interface related │ └ ─ config. Js / / environment configuration │ └ ─ index. The js │ └ ─ request. Js / / network request ├ ─ ttcomponents / / headlines applet custom components storage directory │ ├─ Main.js │ ├─ app.vue │ ├─ app.vue Used to configure the App global style and listening ├ ─ the manifest. The json / / configure application name, version appid, logo, and other packaging information └ ─ pages. The json / / routing configuration page, the navigation bar, TAB page class informationCopy the code

Run the project

Want to run to which platform small program, first need to fill in the corresponding APPID, IDE path

NPM run dev:mp-toutiao //Copy the code

The following message is displayed:

Now open bytedance IDE for import operation, you can see the page ~~~

Tips: When opening uni-app-compiled applets using bytedance compiler, you must import them instead of creating new ones, which will default to code snippets, although it will preview in real time but will result in uploads

Specific page development

The homepage development

  • Effect of the page

  • Home directory structure

The directory structure of the other pages in the project is the same as that of the home page.

├ ─ pages │ ├ ─ index │ │ └ ─ components │ │ └ ─ vuex │ │ │ └ ─ index. The js/logic/front page │ │ └ ─ index. The vueCopy the code
  • We use Vuex to manage status. Each page has its own VUex, in which index.js stores the relevant logic of the corresponding page. In order to avoid frequent directory changes, state, mutations and actions are put in one file, and vuex modularization is enabled when used, as follows
const IndexPage = {
    namespaced: true, // Enable modular vuex state: {... Open mutations: {open mutations}, mutations: {... // Some methods}, actions: {... // Request related}}exportDefault IndexPage // Finally export IndexPageCopy the code
  • Vuex of each page is uniformly placed in store
import Vue from 'vue'
import Vuex from 'vuex'

import IndexPage from '.. /pages/index/vuex'
import AddressSearch from '.. /pages/address/vuex/index'
import CityListPage from '.. /pages/city-list/vuex/index'Vue.use(Vuex) const store = new Vuex.Store({ state: { ... Mutations: {}, mutations: {}, actions: {}, modules: Vuex CityListPage, vuex CityListPage, vuex CityListPage,})export default store
Copy the code
  • Finally, reference it in main.js
import Vue from 'vue'
import App from './App'
import store from './store'

Vue.config.productionTip = false

App.mpType = 'app'const app = new Vue({ ... App, store }) app.$mount(a)Copy the code

The complete home page logical interaction framework is built successfully, the following is the development of the home page encountered problems

Problems encountered in homepage development

  • Using swiper, write child component, parent component because no effect

Cause: Import swiper from “.. /.. / components/swiper/swiper “, leading to the custom swiper coverage, so don’t show

解决 : import uniSwiper from “.. /.. / components/swiper/swiper “, not the original component naming conflicts

  • Go to Baidu small program header error

Cause: Baidu set HTTP request header if there are Chinese characters

Solution: Use conditional compilation, if it is baidu small program need encodeURI, or delete the Chinese part of the header

  • Uni-app image tag does not support dynamic image import on the applet side
<image class= <image class="tip_icon" src="/static/sender{{endPoint.address ? '' : '_default'}}.png"/>

Copy the code
// Add <image class="tip_icon" src="/static/sender.png"/>
Copy the code
  • Uni.getlocation () can only get latitude and longitude
  • Non-h5 platforms: Key does not support expressions

    Because: the key =”timer__${idx}“, the console will warn at compile time, but does not affect the page
<view 
    class="column_item" 
    v-for="(item, idx) in item" 
    :key="`timer__${idx}`"/ / to: key ="idx"> {{item =="Use the car immediately." ? "" : index == 1 ? "When" : index == 2 ? "Points" : ""}}
</view>
Copy the code
  • When the parent and child components send parameters, no error message is displayed if the type definition is incorrect. Therefore, if null is encountered, you can check whether the type definition is inconsistent
  • Watch in uni-app does not support listening applets, as shown below
watch: {
    searchType (to) {
      if(to) {// Backfill the starting information if it is the starting information otherwise backfill the destination informationif (to === SEARCH_TYPE.START) {
          this.detailAddress = this.startAddress.detailAddress || ' '
        } else {
          this.detailAddress = this.endAddress.detailAddress || ' '}}}}Copy the code

to

mounted () {
	if (this.searchType === SEARCH_TYPE.START) {
		this.detailAddress = this.startAddress.detailAddress || ' '
	} else {
		this.detailAddress = this.endAddress.detailAddress || ' '}}Copy the code

Personal Center Development

  • Effect of the page



    Personal center mainly involves H5 page and small program authorization login function. So the main part is the implementation of webView.

  • The realization of the webview
// template
<web-view id='web-view' v-if='src' :src='src' @bindmessage='onmessage'></web-view>
Copy the code
onLoad (options) {
    console.log('Parameters obtained from H5 entry page', options)
    let { src, needLogin} = options
    if(! needLogin){ this.src = decodeURIComponent(src)return} this.fetchtempToken (SRC)}Copy the code

If the login H5 is not needed, we can directly assign the value to SRC. If the login page can be accessed normally, we need to obtain the temporary token first. After obtaining the temporary token, we send it back to the server and jump in the form of redirectUrl in the middle page.

Problems encountered in personal center development

  • To pass information to a web page, use the Headline API’s BindMessage

“When a web page is sent to the widget postMessage, it will trigger and receive a message at certain moments (widget back, component destruction, sharing).”

// Call H5 onMessage (e) {let { phoneNumber, name } = e.detail
	if(name == 'makePhoneCall'){
		uni.makePhoneCall({
			number: phoneNumber
		})
	}
}
Copy the code

Note that the BindMessage property of the Web-View is not real-time

  • The calling function on the real phone doesn’t work
Uni. makePhoneCall({phoneNumber:'114'});

Copy the code

Solution: Change the tt start of the headline API

// Tt.makephonecall ({phoneNumber:'114'});
Copy the code

Log in to develop

  • Headline authorized login effect

  • Baidu authorized login effect

  • Obtain the service provider information. 2. Call uni.getProvider to obtain the authorization code. Get the user’s mobile phonenumber (where the user logs in to toutiao App) 4. Get the user’s information from @getPhonenumber callback 5. Invoking the Authorization Login service API 6. Obtain the token and OpenID information

// template
<view class="login-page">
	<view class="title">
		<view class="h-line"></view>
		<view class="page-title"</view> <view class="h-line"></view>
	</view>
	<view class="authLogin-wrapper"> <! --#ifdef MP-BAIDU -->
		<button type="default" open-type="getPhoneNumber" @getphonenumber="authLoginTap" class="login authLogin"</button> <! --#endif --><! --#ifdef MP-TOUTIAO -->
		<button 
			type="default" 
			class="login authLogin"
			open-type="getPhoneNumber"
			@getphonenumber="onGetPhoneNumber"</button> <! --#endif -->
	</view>
</view>
Copy the code
// Call the authorization code method to finish renderingmounted () {
	this.getCode()
}
Copy the code
// Get the authorization code method asyncgetCode () {
	const [ errorProvider, provider ] = await uni.getProvider({ service: 'oauth' })

	if (errorProvider) {
		console.log('Failed to get provider')
		return 
	}

	const [ errLogin, data ] =	await uni.login({
		provider: provider.provider[0],
		force: true
	})

	if (errLogin) {
		console.log('Failed to get code') // Failed operations, prompts, etcreturn} const { code } = data this.code = code }, Async onGetPhoneNumber ({detail}) {const {errMsg} = detail // Authorization failedif (errMsg.indexOf('auth deny') > -1) {// Cancel authorization for mobile verification code loginreturn} try {// call service authorization interface const {data} = await authLogin({code: this.code,... detail, })if(data.code === SUCCESS) {// Save token, openID, etc. // update personal information again}else{// failed message etc}} catch (error) {// Failed login exception handling}}, // Baidu get user information the same headlines...Copy the code

Problems encountered during login development

Checkbox-group error is introduced during mobile verification code development, as shown in the following figure:

Cause: Components: {[checkbox. name]: CheckBox} Importing components is not supported

Publish to the test environment

Take Bytedance as an example. Open the Bytedance developer tool, find upload in the toolbar, fill in the version number, and publish. The version number does not conflict with the previous one. Tips: As mentioned earlier, there is no upload button for new code snippets in the developer tools, you need to import the project.

After the successful upload, it will prompt you to enter the small program developer platform, and you can now see the developer’s version.

The above two-dimensional code can only be used as the version of the physical examination to scan.

Publish to a formal environment

  • Prepare by configuring the relevant online domain name in the background
  • Switch to the online environment
// Environment-related configurationsexportConst ENV = {const ENV = {'rd'// TEST environment TEST:'test', // BOX:'box', // ONLINE environment:'online'} // Environment switchexport function getCurrentEnv() {
  returnEnv.online // Switch to ONLINE}Copy the code
  • Click Upload in developer tools
  • Go to the small program developer platform to review the release
  • It can be found in the top search bar after the launch, but tiktok is currently only available on Android.

conclusion

The above is part of the development of Uni-App Bytedance and Baidu Mini program. I believe that you have a preliminary understanding of uni-App practical mini program, and welcome your comments, exchanges and common progress

Sweep code experience

Go to toutiao app and search for “Kuaigou Taxi mini program” or use Toutiao Scan to experience ~

Pay attention to our