I. Environment construction
Create projects quickly using the HBuilderX visual interface, and HBuilderX built-in handles relevant environment dependencies.
-
HBuilderX: Built-in UNI-app editor and project template, download address
-
Wechat developer tools: debug preview tools. Download address
2. Create uni-APP project
create
In the HBuilderX editor, click File in the toolbar -> New -> Project:
Select UNI-app, enter the project name, there are many templates, choose what you need. For the convenience of later expression, the ColorUI template is first created here, for the convenience of reference ColorUI in the future. Then create a default template, this default template file is very small, convenient for free development later. As shown in the following two figures.
Project directory
file | role |
---|---|
pages.json | Configure page information such as routing, navigation bar, and tabs |
manifest.json | Configure the application name, APPID, logo, and version |
App.vue | Application configuration, used to configure the App global style and listen to the application life cycle |
main.js | Vue initializes the entry file |
The static directory | Store static resources (such as images and videos) referenced by applications. Note that static resources can only be stored here |
Pages directory | Directory for storing service page files |
Components directory | Directory for storing component files |
Note: During development, when you write a login feature, you need to go to a page frequently and change it several times, and you need the login information every time you change it, so it is very troublesome. You need to start from login until you get to this screen. In this case, you can use condition.
Now let’s introduce themcondition
:
Condition startup mode configuration, effective only during development, is used to simulate direct page scenarios, such as: after the small program is forwarded, the user clicks on the opened page.
Attribute Description:
attribute | type | If required | describe |
---|---|---|---|
current | Number | is | The index value of the list node for the currently active schema |
list | Array | is | List of startup modes |
The list:
attribute | type | If required | describe |
---|---|---|---|
name | String | is | Startup Mode name |
path | String | is | Startup page Path |
query | String | no | The startup parameters are available in the onLoad function of the page |
The configuration page can be opened directly when running on the real computer in 5+App. The compilation mode needs to be manually changed in wechat developer tools. The process is as follows: wechat development Tools -> Tools -> Compilation configuration -> Find the name configured in condition.
Condition is configured in pages. Josn as follows:
"condition": {// Mode configuration, effective only during development"current": 0, // Current active schema (index of list)"list": [{
"name": "jingdian_detail"// The schema name"path": "pages/jingdian_detail/jingdian_detail"// Start page, mandatory"query": "id=5d1483336d724301607b2c23"// The startup parameters are obtained in the onLoad function of the page. }}]Copy the code
Iii. Reference ColorUI
With the template created in step 2, we are ready to reference it.
The introduction of ColorUI
First copy the ColorUI directory in the ColorUI project directory and paste it into the root directory of the Demo project, the same as the Pages directory.
Use the top action bar
If you like the custom navigationBar in ColorUI, that is, the Cu-Custom component, you need to import it in main.js in the demo project. The cu-Custom component is recommended.
/* demo/main.js */
import cuCustom from './colorui/components/cu-custom.vue'
Vue.component('cu-custom',cuCustom)
Copy the code
The following is the status bar of ColorUI:
You can directly copy the app. vue file in the ColorUI project because it sets the cu-Custom component height and defines the global color. You also need to remove the pages. Json configuration from the system navigation bar. (After custom is opened, no navigation bar is displayed in all Windows)
"globalStyle": {
"navigationStyle": "custom"
},
Copy the code
If you don’t want to use the Cu-custom component, you can introduce these two sentences directly in the app. vue file
. And of course you have to add it up here.
@import "colorui/main.css";
@import "colorui/icon.css";
Copy the code
For an introduction to referencing ColorUI, see also Referencing ColorUI
Bottom operation bar.
/ * ColorUI/pages/index/index. The vue * / < template > < view > / / using v - the if condition judgment, // If you go to the bottom of the action bar Elements -> Basics, Components -> Component or Extension -> Plugin, the corresponding main screen will appear. As shown above. <basics v-if="PageCur=='basics'"></basics>
<components v-if="PageCur=='component'"></components>
<plugin v-if="PageCur=='plugin'"></plugin> // The "element", "component" and "extension" operations are all bound to a click event NavChange, which changes the path of the image by setting the PageCur value and combining it with the :class attribute, thus changing the color of the button <view class="cu-bar tabbar bg-white shadow foot">
<view class="action" @click="NavChange" data-cur="basics">
<view class='cuIcon-cu-image'>
<image :src="'/static/tabbar/basics' + [PageCur=='basics'?'_cur':''] + '.png'"></image>
</view>
<view :class="PageCur=='basics'? 'text-green':'text-gray'"</view> </view> <view class="action" @click="NavChange" data-cur="component">
<view class='cuIcon-cu-image'>
<image :src="'/static/tabbar/component' + [PageCur == 'component'?'_cur':''] + '.png'"></image>
</view>
<view :class="PageCur=='component'? 'text-green':'text-gray'"</view> </view> <view class="action" @click="NavChange" data-cur="plugin">
<view class='cuIcon-cu-image'>
<image :src="'/static/tabbar/plugin' + [PageCur == 'plugin'?'_cur':''] + '.png'"></image>
</view>
<view :class="PageCur=='plugin'? 'text-green':'text-gray'"> extension < / view > < / view > < / view > < / view > < / template > < script >export default {
data() {
return {
PageCur: 'basics'
}
},
methods: {
NavChange: function(e) {
this.PageCur = e.currentTarget.dataset.cur
}
}
}
</script>
<style>
</style>
Copy the code
When one of the three buttons of “element”, “component” and “extension” is clicked, the corresponding page will appear. The reason is that the following code will be introduced in the project mian. Js of ColorUI:
import basics from './pages/basics/home.vue'
Vue.component('basics',basics)
import components from './pages/component/home.vue'
Vue.component('components',components)
import plugin from './pages/plugin/home.vue'
Vue.component('plugin',plugin)
Copy the code
There are other ways to look at this bottom bar
Fourth, combined with the implementation of back-end basic operations
Realize user login and registration
Simple registration
Up-front code
<view class="list">
<view class="list-call">
<text class="cuIcon-mobile text-style "></text>
<input class="biaoti" v-model="phoneNum" type="number" maxlength="11" placeholder="Enter your mobile phone number" />
</view>
<view class="list-call">
<text class="cuIcon-lock text-style "></text>
<input class="biaoti" v-model="password" type="text"
maxlength="32" placeholder="Enter your password" :password='tfpsw' />
<image class="img"
:src="showPassword? '.. /.. /static/login-reg-forget/op.png':'.. /.. /static/login-reg-forget/cl.png'"
@tap="display"></image>
</view>
<view class="list-call">
<text class="cuIcon-people text-style "></text>
<input class="biaoti" v-model="username" type="text" placeholder="Enter a user name" />
</view>
</view>
<view class="dlbutton bg-color" hover-class="dlbutton-hover" @tap="bindReg"</text> </view> <script>export default {
data() {
return {
phoneNum:' ',
password:' ',
username:' ',
tfpsw:true,
xieyi:true,
showPassword:false}; }, methods: {// password display or horsedisplay() { this.showPassword = ! this.showPassword this.tfpsw =! This.tfpsw}, // protocolxieyitong(){ this.xieyi = ! this.xieyi; } / / registeredbindReg() {// Simple validationif (this.xieyi == false) {
uni.showToast({
icon: 'none',
title: 'Please read the Software User Agreement'
});
return;
}
if(this.phoneNum.length ! =11) { uni.showToast({ icon:'none',
title: 'Incorrect mobile number'
});
return;
}
if (this.password.length < 6) {
uni.showToast({
icon: 'none',
title: 'Password number at least 6'
});
return; Request ({//this.websiteUrl is the global API, set the url in mian'/user/signup',
data: {
mobile:this.phoneNum,
password:this.password,
username:this.username,
},
method: 'POST',
dataType:'json',
success: (res) => {
if(res.statusCode==200){
uni.reLaunch({
url: ".. /login/login"}); uni.showToast({title:"Registration successful!",icon:'none'});
}else{
uni.showToast({title:"Registration failed",icon:'wrong'}); }}}); }}} </script> //Copy the code
Uni. Request is to initiate a web request to see more, and HERE I will mention the URL: this.websiteurl +’/user/signup’, this. WebsiteUrl in this URL, this.
// Set the global API address vue.prototype. websiteUrl ='http://10.4.14.132:7000';
Copy the code
10.4.14.132 is the local IPV4 address, and :7000 is the back-end port number.
Combined with the running interface, more intuitive (the picture is a little big……)
landing
This time for a mobile phone type, now a lot smaller, first look at the interface!
<view class="list">
<view class="list-call">
<text class="cuIcon-mobile text-style "></text>
<input class="biaoti" v-model="phoneNum" type="number" maxlength="11" placeholder="Enter your mobile phone number" />
</view>
<view class="list-call">
<text class="cuIcon-lock text-style "></text>
<input class="biaoti" v-model="password" type="text" maxlength="32" placeholder="Enter your password" password="true" />
</view>
</view>
<view class="dlbutton bg-color" hover-class="dlbutton-hover" @tap="bindLogin()"</text> </view> <script>export default {
data() {
return {
phoneNum: ' ',
password: ' '
};
},
methods: {
bindLogin() {
if(this.phoneNum.length ! = 11) { uni.showToast({ icon:'none',
title: 'Incorrect mobile number'
});
return;
}
if (this.password.length < 6) {
uni.showToast({
icon: 'none',
title: 'Incorrect password'
});
return;
}
uni.request({
url: this.websiteUrl+'/user/login',
data: {
mobile: this.phoneNum,
password: this.password
},
method: 'POST',
dataType: 'json',
success: (res) => {
console.log("Login returns data",res);
if (res.data.data.code == 1) {
uni.showToast({
title: "Login successful!",
icon: 'none'
});
uni.setStorageSync('token', res.data.data.token);
uni.setStorageSync('loginUser',res.data.data.userinfo);
uni.reLaunch({
url: ".. /index/index"}); }else {
uni.showToast({
title: "Login failed!",
icon: 'wrong'}); }}}); } } } </script>Copy the code
SetStorageSync is used when logging in. SetStorageSync stores data in the key specified in the local cache and overwrites the content corresponding to the key. This is a synchronization interface. When using the uni.setStoragesync interface to store data in the local cache, uni.getStoragesync is required to retrieve information. To view more
Class and style binding
The class and style bindings will be used in the development.
Class supports the following syntax:
<view :class="{ active: isActive }">111</view>
<view class="static" v-bind:class="{ active: isActive, 'text-danger': hasError }">222</view>
<view class="static" :class="[activeClass, errorClass]">333</view>
<view class="static" v-bind:class="[isActive ? activeClass : '', errorClass]">444</view>
<view class="static" v-bind:class="[{ active: isActive }, errorClass]">555</view>
Copy the code
Syntax supported by style:
<view v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }">666</view>
<view v-bind:style="[{ color: activeColor, fontSize: fontSize + 'px' }]">777</view>
Copy the code
Let’s write an example:
Before we submit the “application”, the color of the button is green, in line with the user’s custom. When the button is clicked, a series of actions are performed, such as interacting with the backend. This example is simple, just plain changing styles.
html:
<button class="static"
:class="[isSubmit ? Submited: '', NoSubmit]"
@click="submitFile">{{text}}</button>
Copy the code
Js: It must be registered in data and then used in class so that it will be rendered.
export default {
data() {
return {
Submited: 'Submited',
NoSubmit: 'NoSubmit',
isSubmit:false,
text:'application'
}
},
methods: {
submitFile(){
this.text ='Applied for';
this.isSubmit = true; }}}Copy the code
Page jump
Here is a brief description of the route jump problem, details can see the official website.
Uni.navigateto () : Jump to non-tarbar pages
NavigateBack (uni. NavigateBack) navigateBack (uni. NavigateBack) navigateBack (uni. NavigateBack)
Example:
NavigateTo ({url: uni.navigateTo({url:'test? id=1&name=uniapp'
});
Copy the code
// Accept arguments on the test.vue pageexport default {
onLoad: function(option) {// Option is object, which serializes console.log(option.id) from the previous page; // Prints out the arguments passed from the previous page. console.log(option.name); // Prints out the arguments passed from the previous page. }}Copy the code
Uni.redirectto () : Jumps to non-tarbar pages
Close the current page and switch to a page in the application. Example:
uni.redirectTo({
url: 'test? id=1'
});
Copy the code
uni.reLaunch()
Close all pages and open to a page within the app.
Intra-application page path to which you want to jump. Parameters can be set after the path. Between parameters and paths? Parameter keys and parameter values are connected with =, different parameters are separated with &; If the path? Key =value&key2=value2. If the path to the page is tabBar, the parameter cannot be added.
uni.switchTab(OBJECT)
Jump to the tabBar page and close all other non-Tabbar pages. Example:
pages.json
{
"tabBar": {
"list": [{
"pagePath": "pages/index/index"."text": "Home page"}, {"pagePath": "pages/other/other"."text": "Other"}}}]Copy the code
other.vue
uni.switchTab({
url: '/pages/index/index'
});
Copy the code
Summary:
- NavigateTo, redirectTo can only open non-Tabbar pages.
- SwitchTab Opens only tabBar pages.
- ReLaunch can open any page.
- The tabBar at the bottom of the page is determined by the page, that is, any page defined as a tabBar has a tabBar at the bottom.
- You can’t jump to pages in app. vue.
Page and transfer
For example, if you click the card of this scenic spot, you will enter the details page of this scenic spot. In this process, you will use the parameter transfer of the page.
The main code is as follows:
//index.vue
<template>
<view class="cu-card case " v-for="(item, index) in jingdian" :key="index" @click="jd_Detial(item)">
<view class="cu-item shadow">
<view class="image">
<image :src="item.img" mode="widthFix"></image>
<view class="cu-tag bg-red">Hot</view>
</view>
<view class="cu-list menu-avatar">
<view class="cu-item">
<view class="content flex-sub" style="left: 20px;">
<view class="text-grey">{{item.name}}</view>
<view class="text-gray text-sm flex justify-between">
<view class="text-gray text-sm">
<text class="icon-icon_like-copy margin-lr-xs"Collection < / > < / text > view > < view > < view > < view > < view > < view > < view > < / template > < script >export default {
data() {
return {
jingdian:[]
}
},
created:functionUni. Request ({url: this.websiteurl +'/api/showCityTickets/'+ this.cityId,
method: 'GET',
dataType: 'json',
success: (res) => {
this.jingdian = res.data.data;
}
})
} catch (e) {
// error
console.log('error',e)
}
},
methods: {
jd_Detial(item){
console.log('id',item._id); NavigateTo (uni.navigateTo({url:".. /jingdian_detail/jingdian_detail? id=" + item._id
})
}
}
}
</script>
Copy the code
Below is the details page of jingdian_detail.vue
jingdian_detail.vue
onLoad()
_id
onLoad(options) { var _this = this; this.ticketId = options.id; Uni. Request ({url: this.websiteurl +); uni. Request ({url: this.websiteurl +)'/api/ticketsShowDetial/' + options.id,
method: 'GET',
dataType: 'json',
success: function success(res) {
if(res.statusCode == 200) { _this.detail = res.data.data; }}}); console.log('&&&&&&&&this.detail&&&&&&', this.detail);
}
Copy the code
To obtain position
I have written a simple positioning, just for the convenience of everyone to understand how this function is implemented.
This location can only be tested on the phone, there is no GPS on the H5.
The code:
<template>
<view style="margin: 10px auto;">
<button @click="getLocal()"Longitude :{{longitude}} </p> <p> Latitude: {{address.country+address.province+address.city + address.district+ address.street}}</p> </view> </template> <script>export default {
data() {
return {
latitude:' ', the latitude/longitude:' ',// address:{},// address information}}, methods: {getLocal(){// Get the current location and speed.let that = this;
try{
uni.getLocation({
type: 'wgs84',
geocode:true// Select * from the address list.function(res) {that.latitude = res.latitude that.longitude = res.longitude that.address = res.address // view map uni.openLocation({ latitude: that.latitude, longitude: that.longitude, success:function () {
console.log('Open map success'); }}); }, fail:function(res){
console.log("fail====",res)
}
});
}catch(e){
console.log("error",e)
}
}
}
}
Copy the code
Click the location button to get the local latitude and longitude and detailed address, and then automatically jump to the map page.
To obtain position
Look at the map
Run and publish
For operation and release, there is an introduction in “Getting Started” on the official website, please click to view