In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly explains "how to use mpvue+koa+mongodb to develop mall Mini Program", interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Next, let the editor take you to learn how to develop mall Mini Program with mpvue+koa+mongodb.
Technology stack
Front end: WeChat Mini Programs, mpvue
Backend: koa
Database: mongodb Database Visualization tool: Robo3T
Mall Mini Program starts to run
A basic mall Mini Program, including the front-end home page, classification, shopping cart, my (order) four tab pages, the back-end data definition, classification, and access. Each has its own color, and I'll introduce some of the main features below, the comparison of native Mini Program and vue.js pits, and the functional applications of back-end databases. If you want to know or have any questions, you can go to the source code of the work.
Results sharing 1. Foreground pages and functions
1. On component encapsulation
Take Chestnut as an example, the home page consists of three parts: head rotation recommendation + middle horizontal slide recommendation + vertical scrolling product list. These three parts are the necessary functions of almost all mall app. As we all know, such functional components are basically indispensable on each app. The first thing to learn from vue is the high reusability of component code. It is quite convenient to reuse and migrate some components to other components or pages without changing the code or a small amount of code. For swiper and scroll, which still support native Mini Program in mpvue components, this function can be done efficiently for developers who are familiar with Mini Program and vue after they are compatible.
Finally, the main page file is composed of components, which is highly readable. For beginners, the idea of module encapsulation is the first to have.
-recommend to you-hot products-
{console.log (res); this.goods = res.data.data;}})},} copy code
The ordinary function this points to the context in which the function is running, that is, the context in which it is called, so here, it doesn't really matter whether the lifecycle function is an ordinary function or an arrow function, because its definition environment is the same as the running environment, so you can also get the data, properties and methods in the vue instance. In the arrow function, this points to the outermost block of code that defines it, () = > {} is equivalent to function () {} .bind (this); so this, of course, points to the vue instance. At first, the problem of this pointing was not taken into account. In wx.request ({}), success used a common function, and the result kept reporting an error of "goods is not defined". It was solved with the arrow function. At first, the this of the ordinary function pointed to the context of getGoodsList (), so there was no way to get the value.
5.onLoad and onShow
When you click on the item on the home page to jump to the details page, onLoad () cannot get the updated data.
First of all, although onLoad: function (options) this is acceptable, but this is only loaded once, not the effect I want, I need to jump in from this page (without closing) to another page and receive the data of the corresponding product.
Therefore, you need to put the code inside the onshow, and each time the page is loaded, it will query the current status, query the sub-objects of the corresponding data, and update and render to the details page.
OnShow: function (options) {/ / console.log (this.styleobject) / / console.log (options) wx.getStorage ({key: 'shopCarInfo', success: (res) = > {/ / success console.log (`initshopCarInfo:$ {res.data} `) this.shopCarInfo = res.data This.shopNum = res.data.shopNum}}) wx.request ({url: 'http://localhost:3030/shop/goods/detail',// requests the data of the detail data table method:' POST', data: {id: options.id}, success: res = > {/ / console.log (res); const dataInfo = res.data.data.basicInfo This.saveShopCar = dataInfo; this.goodsDetail.name = dataInfo.name; this.goodsDetail.minPrice = dataInfo.minPrice; this.goodsDetail.goodsDescribe = dataInfo.characteristic; let goodsLabel = this.goodsLabel goodsLabel = res.data.data; / / console.log (goodsLabel); this.selectSizePrice = dataInfo.minPrice; this.goodsLabel.pic = dataInfo.pic; this.goodsLabel.name = dataInfo.name This.buyNumMax = dataInfo.stores; this.buyNumMin = (dataInfo.stores > 0)? 1: 0;}})} copy the code
Learn about Mini Program onLoad and onShow lifecycle functions:
OnLoad: lifecycle function-listens to Mini Program initialization. When Mini Program initialization is completed, onLoadh will be triggered (only once globally).
OnShow: lifecycle function-listening to Mini Program shows that onShow will be triggered when Mini Program is started or displayed in the foreground from the background.
Second, background database and data access 1. Set up HTTP services
In the global configuration file: 1). Introduce koa and instantiate
Const Koa = require ('koa'); const app = new Koa () copy the code
2) .app.listen (port number): create and return the HTTP server, passing the given parameter to Server#listen ().
Const Koa = require ('koa'); / / introduce koa framework const app = new Koa (); app.listen (3000); the app.listen () method here is just grammatical sugar for the following methods: const http = require (' http'); const Koa = require ('koa'); const app = new Koa (); http.createServer (app.callback ()) .sugar (3000); copy code
With this basic configuration, we can use the http://localhost3030+ request address parameter to get the value of the database.
2.Koa-router routing middleware
Koa-router is a commonly used routing library for koa.
If you rely on ctx.request.url to manually deal with routing, you will write a lot of processing code. At this time, you need the corresponding routing middleware to control the routing. Here we introduce a better routing middleware koa-router.
Route switching drives interface switching and "data" interface.
3. Establish an object model
Before building the function library, let's talk about object modeling.
Mongoose is an object model tool for convenient operation of mongodb in node.js asynchronous environment. The npm package encapsulates methods for manipulating mongodb.
Mongoose has two characteristics:
1. Design the non-relational number through the idea of relational database.
2. Based on mongodb driver, simplify operation
Const mongoose = require ('mongoose') const db = mongoose.createConnection (' mongodb://localhost/shop') / / establish a connection to the shop database (shop is my local database name) replication code
In the local database shop, there are five data tables: "address Management", "Product details", "order details", "Product list" and "user list".
The Schema interface defines the data model:
Schema defines the structure of the database. Similar to the data definition when creating a table (you can define not only the structure and properties of the document, but also the instance method, static model method, composite index, etc.), each Schema is mapped to a collection in mongodb, but Schema does not have the ability to manipulate the database.
The mapping of the data table to the object also has the effect of checking whether each set of data meets the conditions defined in the model. At the same time, each object is mapped into a data report, and the object can be used for saving operations, which is equivalent to manipulating the data table, rather than as tedious as the mysql command line.
Take the Commodity list data sheet as an example:
/ / the model is defined through the Schema interface. Var Schema = mongoose.Schema Const listSchema = new Schema ({barCode: String, categoryId: Number, characteristic: String, commission: Number, commissionType: Number, dateAdd: String, dateStart: String, id: Schema.Types.ObjectId, logisticsId: Number, minPrice: Number, minScore: Number, name: String, numberFav: Number, numberGoodReputation: Number, numberOrders: Number, originalPrice: Number, paixu: Number, Number: pic, pic: pic, String: String, String: String,: Status: Number, statusStr: String, stores: Number, userId: Number, videoId: String, views: Number, weight: Number,}) copy the code
The type of data item needed in the data table is defined. When the data is passed into the data table, it will correspond to one by one:
4.koa-router "routing library" const Router = require ('koa-router') () / / introduce koa-routerconst router = new Router () / / create router instance object / / register routing router.post ('/ shop/goods/list', async (ctx, next) = > {const params = ctx.request.body / / fetch the data of Goods with the model of 'listSchema' const Goods = db.db.model (' Goods', db.listSchema) / / the first 'db' is customized from require, and the second' db' is fetched to the database connected to mongodb Model refers to entity data (the data under this field is obtained according to schema and then passed to Goods)) ctx.body = await new Promise ((resolve, reject) = > {/ / ctx.body is the abbreviation of ctx.response.body, which refers to response data / / async Wait until the data is obtained before sending the body to if (params.categoryId) {Goods.find ({categoryId: params.categoryId}, (err, docs) = > {if (err) {reject (err)} resolve ({code: 0, errMsg: 'success') Data: docs})} else {Goods.find ((err, docs) = > {if (err) {reject (err)} resolve ({code: 0, errMsg: 'success', data: docs}) copy the code
All database operations are asynchronous, so you need to encapsulate promise so that the local shop database can be accessed through the POST "http://localhost3030/shop/goods/list". Incidentally, the use of "ctx", the ctx (context) context, we all know that there are request (request) objects and respones (response) objects in node.js. Koa encapsulates these two objects in a ctx object. The parameter ctx is a variable that encapsulates request and response passed in by koa, through which we can access request and response (the front end requests http to get data through ajax) We can request or to get the data in the database through ctx.
The Ctx.body attribute is the content sent to the user
Body is the response body in http protocol, and header is the response header.
Ctx.body = ctx.res.body = ctx.response.body
5. Model layer settings for data caching
1)。 Why do you do data caching?
Here, I have to mention the importance of data caching. Although I get the data from the local database, due to the large amount of data needed, and the performance optimization mentioned earlier has not been completed, there is still a certain request time every time. There is no need to request the backend every time you open it. Rendering the page is slow, so you need to cache the frequently used data locally, which can greatly improve the rendering speed of the page.
2)。 Set up the model layer
SetGoodsList: function (saveHidden, total, allSelect, noSelect, list) {this.saveHidden = saveHidden, this.totalPrice = total, this.allSelect = allSelect, this.noSelect = noSelect, this.goodsList = list var shopCarInfo = {}; var tempNumber = 0; var list = []; shopCarInfo.shoplist = list; for (var I = 0; I
< list.length; i++) { tempNumber = tempNumber + list[i].number } shopCarInfo.shopNum = tempNumber; wx.setStorage({ key: "shopCarInfo", data: shopCarInfo }) },复制代码 将需要做本地存储数据的方法封装成一个方法模型,当需要做本地存储时,直接做引用,如今vue、react中多用到的架构思想,都对模型层封装有一定的要求。 bindAllSelect() { var list = this.goodsList; var currentAllSelect = this.allSelect if (currentAllSelect) { list.forEach((item) =>{item.active = false})} else {list.forEach ((item) = > {item.active = true})} this.setGoodsList (this.getSaveHide (), this.totalPrice (),! currentAllSelect, this.noSelect (), list) }, copy the code here, I believe that everyone on "how to use mpvue+koa+mongodb development mall Mini Program" have a deeper understanding, might as well to practical operation it! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.