Every time I write an article, I always feel a lot of emotion. In the face of success, we always hold higher expectations, always want to be impatient to get the fruits of victory. But every success cannot come easily to us. Almost every time it requires a great deal of patience, diligence, and even paranoid persistence. I’ve been moving into this market ever since mini apps came out. Not because of his enthusiasm, but because of his interest in learning, always wanting to explore new knowledge. It is with this kind of motivation that I have been able to stick to it. From my last article “didi summer, small program car” published so far, has been half a month long. I made a lot of good friends. They are cheerful and witty. Treat others with your own unadorned enthusiasm. They did not spare any ink for my campaign, to encourage me and correction. I also want to thank Ms. Huang yi for giving me the interview opportunity and the wonderful courses in MOOCs. Back to the topic, today we bring you meituan takeout micro channel small program, based on MPVue development. It is only three months since MPVue was launched, so I will explain every detail in detail, hoping to help you who feel frustrated on the way to MPvue. It’s hot, let’s order a takeaway!
preface
Learning is like a big mountain. People climb it by different roads and share the scenery they see. You don’t necessarily see the scenery others see, feel the mood of others. Only by climbing, can we see different scenery and experience more deeply. Therefore, it is recommended to practice a wave.
The technology stack used by the project
- Data requests: flyio.js- a cross-platform HTTP request library that supports browsers, applets, Node, Weex, and promises. This allows you to reuse as much code as possible across multiple ends
- CSS precompiler: Stylus – Node.js-based CSS preprocessor framework
- Data source :EasyMock- Provides mock data for tests
- Overall framework: MPVUE
- Map: Tencent Map API
Download startup Procedure
- 1, git clone github.com/WsmDyj/mpvu…
- 2. Start the installation
# install dependencies
npm install
# serve with hot reload at localhost:8080
npm run dev
# build for production with minification
npm run build
# build for production and view the bundle analyzer report
npm run build --report
Copy the code
- The applets development tools point to the dist directory below
rendering
Even beautiful language can’t match the reality of pictures. Let’s enjoy meituan take-out!
Mpvue and Applets spark (pit trip)
When writing meituan take-out mini program, I stumbled like everyone else. There will always be various problems and stuck between vUE writing and MPVUE writing. Mpvue just came out, effective resources are really few, there is no introduction of a basic project process. So I germinated this article to conceive the whole mpVUE development through this whole project. I may not be able to list all of them, but I will try my best to explain the most common and commonly used areas. Willing to share and help the community.
Data request encapsulation in MPVUE
The most important thing to write a project is data. The whole page comes alive with data, and the data needs to be watered with HTTP requests. The javascript operation of wechat is different from that of the browser. The script logic of the page is run in JsCore, which is a situation without window objects and XmlhttpRequest objects. So jquery, Zepto, axios, and so on couldn’t get into wechat development, and fly did.
- 1. Install flyio.js
npm install flyio
- Create a fly.js file at util for encapsulation
import Vue from 'vue'
var Fly=require("flyio/dist/npm/wx.js"Var fly=new fly (); var fly=new fly (); / / create instances / / add interceptors fly fly. The interceptors. Request. Use ((config, promise) = > {config. Headers ["X-Tag"] ="flyio"; // Add custom headers to all requestsreturnconfig; }) // configure the request base address fly.config.baseurl ="https://www.easy-mock.com/mock/5aded45053796b38dd26e970/"
Vue.prototype.$http=fly // Mount fly on vUE for global useexport default fly
Copy the code
- 3. Wrap a getList method in the root directory main.js. Call this method directly on the page that uses the requested data. Improve code reuse
Vue.prototype.getList = function () {
wx.showLoading({
title: 'Loading',
})
this.$http.get('sell#! method=get').then((res)=>{ this.restaurant = res.data.data.restaurant; // This. Goods = res.data.data. Goods; // This.seller = res.data.data.seller; This.ratings = res.data.data.ratings // comment data.wx.hideloading (); }).catch((e)=>{ console.log(e) }) }Copy the code
By encapsulating the request for data, our project is more than half complete. The next step is to use this data to populate our pages for interaction.
Second, MPVue practical functions in detail
In the following sections, I will explain one by one how mpVue implements location, location search, pull-up load, pull-down refresh, and secondary linkage between items. Let’s focus on the following points.
Mpvue location and location search
Mpvue location and location search with small program similar, we can take a look at my last article, there and detailed address resolution, inverse address resolution, keyword search and so on.
export default QQMapWX;
This can only be used on a page, which is used in conjunction with the wx.getLocation() and wx.Chooselocation () apis provided by wechat applets.
import QQMapWX from ".. /.. /utils/map"; // Import the new js var qqmapsdk; qqmapsdk = new QQMapWX({ key:'DHNBZ-2ZLKK-T7IJJ-AXSQW-WX5L6-A6FJZ'
});
Copy the code
Mpvue pull-up load and pull-down refresh
Mpvue applets are pull-down loaded and pull-up refreshed by onPullDownRefresh and onReachBottom methods
// Partially enable the pull-down refresh, just under main.jsexport default {
config: {
"enablePullDownRefresh": true,}}Copy the code
onReachBottom() {
letnextPage = this.page +1; +1 this.page = nextPage // Update page this.$http.get('sell#! method=get'). Then (= > {(res). This restaurant = [... res. Data. The data. The restaurant,... this restaurant] / / request of new data, }).catch((e)=>{console.log(e)})},onPullDownRefreash(){ this.isShow = ! this.isShow }Copy the code
Secondary linkage is implemented in MPVUE
The idea of realizing this function:
-
1 Left-to-right: Click an item of the left slider to obtain the ID carried by the element, and then dynamically send the ID to the scroll-in-view of the right slider, so that the movement of the element corresponding to the right slider can be set to the top.
-
2 Right to left: compare the scrolling height of the whole right slider with the distance from the top of each category in the right slider to obtain the index of the top category. Then multiply the obtained index by the height of a certain item in the left slider, dynamically assign the value to the scrollTop in the left slider, and control the linkage of the left slider.
Note the following points: (1) RPX is used in WXSS, but the value obtained by scrollTop in JS is PX, so there is a problem of RPX to PX. Based on iPhone6, the conversion formula is as follows:
// percent is the px value of the current device 1rpx. Var percent = res.windowwidth / 750;Copy the code
(2) wechat has its own scroll view UI component, binding scroll events with bindscroll=”scroll”; Use scrollTop =”{{scrollTop}}” to dynamically control the passive scrolling of the left slider. The code is not posted individually, and there are detailed comments in the project. Click here to see
Mpvue component analysis and component communication
To finish a project is not difficult, but to do a good project is to go through countless times of thinking. One of them is to look at the document, the so-called book read changes, its meaning is now. Indeed, when you look at the document over and over again you will find that it is very easy to write, and you will use it immediately. You can click on the VUE document to see more.
Component analysis
What is component analysis? For MPVUE, components are the building blocks that make up a project. Once the components are partitioned, the project is very fast to write. For ease of understanding, two types of components are defined here: page components and functional components. The page component is the complete display of the current page address you see, and it will contain several functional components. There are many functional components of Meituan takeout small program, roughly listed as follows:
- The scoring component, which needs props for: star size, merchant rating
- Shopping cart components: Needed props: selectFoods, deliveryPrice, minPrice, etc
- Announcement component: Every project inevitably releases announcements or pop-ups, which can be pulled out as a component
- Split components: Components can be large with many features, or small, as long as they are commonly used in the project can be pulled out as a component.
- Swiper component: The rotation diagram as a component can reduce the amount of code we have on a page and pull it out as a component, making it easier to maintain later.
Component communication
The props can be used to pass data between components. Here, select Items -> Select Components -> Shopping cart -> Order Details are used to describe how to pass data between components.
- 1 Selecting Components
Props: {food: {// Accept a food, representing which item is selectedtype: Object,
}
},
addCart(event) {
if(! this.food.count){ this.$set(this.food, 'count', 1) // Click the event to pass to the parent component this.food.count = 1; }else{this.food.count++ // merchandise ++}},Copy the code
- 2 the shopping cart
Accept a selectFood via props, which is put locally in the applet to supply to the order page try {wx.setStoragesync ('selectFoods', this.selectFoods)
} catch (e) {
console.log(e)
}
Copy the code
- 3 Order Page
try {
var value = wx.getStorageSync('selectFoods') // Get the stored data and use the concept of synchronizationif (value) {
this.isShow = false; OrderList =value; this.orderList=value; this.orderList=value; }} Catch (e) {console.log(e)};Copy the code
Method calls between parent and child components can passemit
var Event = new Vue(); // Create a new vue instance. Event contains all vue method events.$emit('msg',this.msg); // To send data, the first parameter is the name of the data to be sent, and the second parameter is the current location of the data Event.$on('msg'.function(MSG){// Receive data, the first argument is the name of the data, the name of the second argument is a method, the data operation})Copy the code
remarks
There are many things I want to talk about, such as reference images in mpvue applets must be placed in static files directory, component properties computed. And the use of VUEX in global data. But a person’s energy is really limited, I am also a junior student, recently busy looking for internship company, but also in the research of vUE underlying source code analysis. And that’s pretty much where all the possibilities end. If you like some of the content, you can download it from my Github and study it slowly. Attached here is the address of my project mpvue. Also hope that like-minded and can join the discussion, if what do not know you can directly comment on me, or send me QQ: 972774037 I will also help you answer the first time. I also hope that this will add color to my internship search, and more wonderful VUE projects will be launched in the next period. Please keep following me!!