Meituan applet framework mpvue (flower name: no friends) squatting guide

Meituan applet framework mpvue (flower name: no friends) squatting guide

The first time I came into contact with the applet was probably at the beginning of 2017. At that time, the applet was just on the inside. At that time, it was tossed to death by various restrictions, one-way binding, no promise, limit on the number of requests, limit on the size of the package, all kinds of anti-human. .. Anyway, I feel full of maliciousness. I recently received an engineering applet project. When I was doing technology selection, I picked up the old things and looked at them again. I got familiar with them again. I feel that the applet is still the same. I am working hard, supporting most of the es6 syntax, and a Vue-like mvvm framework wepy, which also supports redux state management, so I roughly built a demo and ran it. Although it is not as sour as vue, it is still Quite ok, at least much more friendly than the native applet syntax.

Then I started to use wepy to build projects and write static pages (because the company's development model is to write static pages first, and wait for the back-end interface to come out before binding data). Although wepy is easier to use than native, there are still many pitfalls. Yes, I won't list them here...

Just when we were about to finish writing the static page, I saw a message on the forum one night that Meituan released a small program framework mpVue (I don’t know why, every time I see this name, I only think of 3 words, No friends, haha), I took a look at the official introduction , and there are some highlights:

  1. The same development experience as vue, including vuex
  2. The ability to convert H5 code into small program object code

That is to say, you can not only develop with the familiar vue syntax, but also directly compile your h5 page into a small program. The project has been open sourced for less than 20 days, and has received nearly 7,000 stars, which can be seen in the world. Bitter Qin for a long time.

I built a demo and ran it. It feels like a work of conscience in the development world. By the way, I copied the static page code of wepy written before and looked at it. I found that with a little change, you can switch from wepy to mpvue smoothly. Come up (the switching time of the entire project is about half a day). Just do what you say, and cut to mpvue on the same day. Until now, the project is nearing the end, and the whole development process is really pleasant.

Bug.... I don't seem to be here to advertise mpvue today, I'm here to find fault..

Let's take a look at some details that I need to pay attention to when I recently developed with mpvue. (Or different from vue)

First, this personal feeling is the biggest pit. In addition to the lack of files, other code syntax errors, etc., the console is quiet most of the time (occasionally it will report an xxx is undefined) This is what I often encounter. .xxx =5 In some cases, an error will be reported, and in some cases there will be no response. Specifically, under which circumstances it will be, and under what circumstances it will not, I have not figured out the rules yet..

once i put

this.dataObject.map(() => { ...这里省略... })

As a result, the front of the map is accidentally exposed, and the actual code becomes

this.dataObjectmap(() => { ...这里省略... })

As a result, I searched for a long time and couldn't find the cause of the problem.

Second, this is also a more uncomfortable place, that is, in the data binding of the template, there is no way to call the methods method in the template syntax (or there is no way to call functions other than computed), some people may say, you can use the computed attribute, then What if I want to pass parameters to the function? See the code below:

<template>
  <view v-for="item in costList" >
    {{formatCost(item)}}
  </view>
</template>

<script>
export default {
  data(){
    return{
      costList:[]
    }
  },
  methods: {
    formatCost(item){
    return item.toFixed(2)
    },
    getData(){
    let arr = [3.255,4.1,5,15]
    this.costList = arr
    }
  }
</script>

At this time, the content {{formatCost(item)}}inside will be rendered as an empty string, the reason is because functions are not supported, and in this case, the computed property cannot be used, unless you want to write a computed for each array element

In this case, my solution is to change the data first when the data is obtained. As in the above example, we can write this in the getData method

let arr = [3.255,4.1,5,15]
// 遍历数组里面的元素,然后格式化一下,添加到 costList里去
arr.map(item => {
    this.costList.push = this.formatCost(item)
})

3. The created life cycle functions in all pages will be executed at one time when the applet is loaded, not every time a page is entered. For example, I have 3 pages

pageA

...省略一些代码...
creatted(){
    console.log('pageA 的 created函数执行')
}

pageB

...省略一些代码...
creatted(){
    console.log('pageB 的 created函数执行')
}

pageC

...省略一些代码...
creatted(){
    console.log('pageC 的 created函数执行')
}

Then, start the applet without entering these 3 pages. Suppose I have an index page now. When we open this page, there will be some output.

pageA 的 created函数执行
pageB 的 created函数执行
pageC 的 created函数执行

This is actually very easy to solve. It is replaced by mounted or onLoad or onReady. When it comes to these functions, by the way, created and mounted are the life cycle of vue (mpvue), while onLoad and onReady are the life cycle of small programs. Cycle, the official description given by mpvue is:

In addition to the life cycle of Vue itself, mpvue is also compatible with the applet life cycle. This part of the life cycle hook comes from the Page of the WeChat applet. Except for special cases, it is not recommended to use the applet life cycle hook.

However, the official life cycle diagram also shows that the onLoad and onReady of the applet are executed earlier than created and mounted, that is to say, if we request data in onLoad and onReady, the white screen time will be relatively reduced. (The white screen mentioned here refers to the interface with unrendered data), and the official did not explain why it is not recommended to use the life cycle of the applet. We also tried to use the life cycle of the applet and found no life problems, so we still compare Tend to give priority to the life cycle of the applet, after all, the user experience is king.

4. The properties mounted on Vue.prototype are undefined in the template syntax and must be calculated by computed before they can be used. When using vue, I like to store the server path of the image in the vue prototype:

import config from './config'
Vue.prototype.$serverPath = config.serverPath

Then we use this in the page

<img :src="$serverPath + 'logo.png'" />

In this way, you can avoid importing the config file on each page. If we release the official version later, we only need to modify the config configuration file here to understand. If this is written in mpvue, the actual rendering will be

<image src="undefinedlogo.png" ></image>

If you want to use it in each page, you can only import it in each page, or return this.$serverPath in computed

5. When using v-for loop, if you want to assign an index to the current item, under vue, in order to save trouble, I usually like to do this

v-for="item,index in list"

Because typing an extra pair of parentheses is really annoying. But it doesn't work under mpvue, you have to write it honestly, otherwise you will get an error.

v-for="(item,index) in list"

6. Set the page header information for each page separately. This function is provided, but the document is not very detailed. After several attempts, I tried it out.

Our entry file main.js (continuing the name of vue, let's call it that for the time being, in fact, I think it should be called a configuration file) can be configured like this, and the official documentation probably says the same

This part of the content comes from the entry files of the app and page, usually main.js, you need to export default { config: {} } in your entry file, this can be recognized by our loader as a configuration, you need Write to json file.

import Vue from 'vue';
import App from './app';

const vueApp = new Vue(App);
vueApp.$mount();

// 这个是我们约定的额外的配置
export default {
    // 这个字段下的数据会被填充到 app.json / page.json
    config: {
        pages: ['static/calendar/calendar', '^pages/list/list'], // Will be filled in webpack
        window: {  // 顶部栏的统一配置
            backgroundTextStyle: 'light',
            navigationBarBackgroundColor: '#455A73',
            navigationBarTitleText: '美团汽车票',
            navigationBarTextStyle: '#fff'
        }
    }
};

At the same time, at this time, we will automatically fill in the pages field in app.json according to the page data of the entry. The pages field can also be customized. It is agreed that pages starting with the ^ symbol will be placed at the top of the array.

We see that the global top bar style can be configured under config.window, but what if we want to specify a style for each page? In fact, the above method is only suitable for configuring the content in app.json. If you want to add a style to each of your pages, you should do this: Add the following in the entry file (main.js) to which the page belongs Content, for example, I want to set a title for the userCenter/index page, it should be added in userCenter/main.js

export default {
  config: {
    navigationBarTitleText: '个人中心',
  }
}

Note that the difference from the global configuration above is that the configuration content navigationBarTitleText is an attribute of config, while in the global configuration, it is an attribute of config.window

Seven, the naming of components, once, I wrote a partial component, why is it called a partial component, because I only use it in a certain page, so for simplicity, I named this component called list.vue, Then refer to the parent component:

<template>
<!-- 省略其他代码 -->
    <list />
</template>
<script>
  import list from './components/list'
  export default {
    components: {list},
    // 省略其他代码
  }
</script>

The component can be displayed normally, the style is no problem, everything looks so normal, but the logic in the component will not be executed. In addition, as mentioned in the first point of this article, no error will be reported, so let me find it easily... After investigation, it is found that it is related to the imported name of the component, which should be the same as the keyword of WeChat.

<template>
<!-- 省略其他代码 -->
    <listA />
</template>
<script>
  import listA from './components/list'
  export default {
    components: {listA},
    // 省略其他代码
  }
</script>

In this way, it can run normally, and out of the list, I am currently stepping on the tabbar, so when I name it now, I see some words that are suspected to be key, and my mind is a bit shadowy. . This should be a WeChat problem. In short, if you encounter it, just write it out in one piece.

8. When the component is loaded for the first time, the content in onShow cannot be executed. It will only be displayed after it is hidden and displayed, but the page will be displayed every time it is entered. For example, we have a code in a component

onLoad () {
  console.log('onLoad')
},
onShow () {
  console.log('onShow')
},
mounted () {
  console.log('mounted')
},

When the page loads, what we expect to print is

onLoad
onShow
mounted

Then actually, just print out

onLoad
mounted

I have raised an Issue to the official regarding this issue, but have not yet received a response

Speaking of this, let's take a look at the page jumping method of the applet. When the applet jumps from one page (calling wx.navigateTo) to another page, it will not destroy the original page, but go to the background. , and execute the code in onHide in the original page, which is why the page path of the applet can only be up to ten layers, because the pages you have visited are normally stored in memory, which is equivalent to keep-alive in vue, if If you allow to jump to a lot of pages, it is easy to cause excessive memory usage.

Of course, we can also use wx.navigateBack wx.redirectTo wx.reLaunch to destroy the page, these three methods will call the onUnload function of the page

9. Canvas placed in scroll-view will not scroll with the page. It seems to be fixed in a certain position, but it can scroll normally in ordinary view. This problem is actually a WeChat problem, and the official document explains this, but when I encountered the problem, I didn’t expect it to be a problem with the WeChat official. I doubted it was my own code, so I created a new project, and then directly tested the official sample code, the same effect. I'm going to give up later and think of other solutions. I didn't expect to see it in thescroll-view组件 bottom of the introduction of the official document- today.

tip: Do not use textarea, map, canvas, video components in scroll-view

Further review of canvas组件the document, found that there are similar tips

tip: Do not use canvas component in scroll-view, swiper, picker-view, movable-view.

The reason why this is also included is that firstly, I have been tricked by this problem for several days, and I am thinking of other solutions, and secondly, various Baidu and Google have found several similar problems these days, but No one answered, I will record it here, hoping that the children's shoes who stepped on this pit later can be found.

10. If the same subcomponent is referenced in two different places, the styles of the two places will not be loaded, but if it is only referenced in one place, there is no problem. Why put this problem at the end? Because this is only the first few versions of the scaffolding have this problem, the latter should not have this problem. I also raised the issue to the official, and the official answer was to regenerate the project with the new version of the scaffolding, but the project was almost finished. At this time, it was regenerated and then copied the code. I felt too tired, so I didn’t bother with it. The attitude of not giving up, finally found the reason, because the earlier version of the scaffolding lacked the plugin webpack-mpvue-asset-plugin, the new version of the cli will automatically add this plugin. See Issue #180 for details

There are also some issues clearly pointed out by the official, which will not be listed here. Interested children's shoes can directly view the official mpvue documentation

In addition, I am doing a basic mpvue tutorial recently. If you are interested in children's shoes, please go to my github mpvue-tutorials . One of your Stars is my biggest motivation.

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326875502&siteId=291194637