How does mpvue develop WeChat mini programs? Introduction to basic knowledge

青灯夜游
Release: 2019-11-25 15:10:16
forward
3362 people have browsed it

mpvue is a front-end framework for developing small programs using Vue.js. The framework is based on the core of Vue.js. mpvue modifies the runtime and compiler implementations of Vue.js so that it can run in a mini program environment, thus introducing a complete Vue.js development experience for mini program development. mp is the abbreviation of mini program.

How does mpvue develop WeChat mini programs? Introduction to basic knowledge

mpvue quick start

①Introduce mpvue template through scaffolding

vue 3.0 alreadydoes not support the vue init command , so you need to install it separately @vue/cli-init. After installation, you can follow the following steps to introduce the mpvue template
npm install -g @vue/cli-init

vue init mpvue/mpvue-quickstart my-project

cd my-project

npm install

npm run dev
Copy after login
npm run dev command will be in the project root directory Generate a dist directory, which is Convert the vue project into a WeChat applet project

② Build a development environment for the applet

WeChat provides a dedicated WeChat Developer Tools are used to develop small programs. You need to download and install WeChat Developer Tools. You also need to apply for a small program ID, namely AppID, because creates small programs through WeChat Developer Tools. The program project needs to fill in the AppID, which can be applied for on the WeChat public platform.

③ Debugging project

Start the WeChat applet project through the WeChat developer tool. The selected project directory is the root directory of the mpvue project, not the generated dist directory. Since WeChat developer tools do not support viewing .vue files, we still have to use our own development tools to debug the source code.

Some usage details of mpvue

① The src directory of mpvue is the same as vue. There is also an App.vue root component, The App.vue root component is just A structure , has no specific content, and the root component has a corresponding main.js file used to render the App.vue root component, that is, introduces App.vue and serves as The Vue constructor creates a Vue instance, then mount, and there is also a app.json file, which is the page global configuration file, used for page registration , tabBar registration, global window style setting, such as:

// App.vue

<script>

export default {
 
}
</script>

<style>
page {
  width: 100%;
  height: 100%;
  background-color: #f7f7f7;
}
</style>
Copy after login

// main.js

import Vue from 'vue'
import App from './App'
Vue.config.productionTip = false
App.mpType = 'app'

const app = new Vue(App)
app.$mount()
Copy after login

// app.json

{
  "pages": [
    "pages/index/main"
  ],
  "tabBar": {
    ......
  },
  "window": {
    "backgroundColor":"#00BFFF",
    "backgroundTextStyle": "light",
    "navigationBarBackgroundColor": "#fff",
    "navigationBarTitleText": "测试",
    "navigationBarTextStyle": "black"
  }
}
Copy after login

② The pages defined in mpvue are placed in the pages directory under the src directory. One page corresponds to one folder, Each page folder needs to have a .vue file and main.js file . The main thing main.js does is, Introduce the .vue corresponding to the current page , then create a Vue instance and mount as a parameter of the Vue constructor, and the name of main.js cannot be changed , can only be main.

/ / main.js

import Vue from 'vue'
import App from './index'

// add this to handle exception
Vue.config.errorHandler = function (err) {
  if (console && console.error) {
    console.error(err)
  }
}

const app = new Vue(App)
app.$mount()
Copy after login
In mpvue, although the name of the .vue file in a page can be arbitrary, the names of .js and .json files are fixed to main. Usually we The .vue file also always uses index.vue. A page usually contains index.vue, main.js, main.json, different pages are distinguished through outer folders, and in the native applet, different pages are also distinguished by outer folders, but the names of the four pages in the folder can be the same as the outer folder, or they can be different, but the names of the four files Must be unified.

Every time a new page is added, the project needs to be restarted, that is, re-executing npm run dev.

WeChat Mini Program Basics and Common API

Click the button to prompt the user whether to authorize and obtain user information

The WeChat applet gives us some buttons

wx global objectJust like a web page running in a browser environment, the browser environment will provide a global window object , the same applet runs in the applet environment,
the applet environment will also provide a global wx object, wx will provide many APIs, such as accessing the network (wx.request({}) ), page jump (wx.redirectTo({})), display loading(wx.showLoading({})), display prompt (wx. showToast({}))etc

微信小程序中发起网络请求
在小程序环境中不能像浏览器环境一个直接提供ajax,而是提供了一个全局的网络请求api,即wx.request(),在小程序环境中只能使用wx.request()发起网络请求,不能使用axios等常用的请求类库,并且wx.request()并不存在跨域问题。使用wx.request()的时候,需要传递一个请求参数配置对象request()方法返回结果并不是一个Promise对象,所以不能通过.then()的方式去处理请求结果,而是在请求配置对象中添加了success、fail、complete等回调函数,在回调函数中可以获取到请求的结果,如:

wx.request({
    url: "http://www.baidu.com", // 请求url地址必填
    data: {
        user: "even li"
    },
    method: "get", // 请求方法
    header: {
        "content-type": "application/json" // 默认值
    },
    success(res) {
        console.log(res.data); // 获取响应数据
    },
    fail(error) {
        console.log(error); // 请求失败
    }
    complete(res) { // 接口调用结束,请求成功或失败都会执行
        console.log(res); // 如果请求成功则res为响应结果res,如果请求失败则res为错误信息error
    }
});
Copy after login
需要注意的是,返回状态码为404也算请求成功一般只有网络异常的时候才算请求失败

跳转页面非tabBar页面
如果想要跳转到某个非tabBar页面,那么可以使用一个全局的api,即wx.redirectTo({}),其作用就是关闭当前页面,跳转到应用内的某个页面。但是不允许跳转到 tabbar 页面。需要传递一个配置对象,主要属性为url,即要跳转页面的路径,可带参数,然后就是success、fail、complete三个回调函数,请处理跳转结果,如:

wx.redirectTo({
    url: "../question/main", // 在某个页面内../相当于pages/
    success() {
    },
    fail() {
    },
    complete() {
    }
});
Copy after login

跳转到tabBar页面
在微信小程序中,tabBar页面是需要特殊的方式跳转的,即使用wx.switchTab({})的方式,其会跳转到 tabBar 页面,并关闭其他所有非 tabBar 页面,其用法同wx.redirectTo({});

wx.switchTab({
   url: "../learn/main", // 在某个页面内../相当于pages/
success() {
    },
    fail() {
    },
    complete() {
    }
});
Copy after login

页面配置文件
小程序的页面配置文件分为全局配置文件app.json与即页面配置main.json. 全局配置文件可配置项比较多,整个配置文件内容要用花括号括起来,也就是说是一个JSON对象,如:

  • pages属性,是一个数组,用于定义小程序用到的页面,数组中每一项对应一个页面,即路径+文件名信息,不需要写后缀,在mpvue中所有页面固定使用main,即每个页面下都会有一个main.js,所以在配置pages时,通常为"pages/页面名/main",位于pages数组第一项表示小程序的初始页面,即小程序运行时显示的页面
  • window属性,即对小程序的窗口样式进行配置,其属性值为一个对象,主要包括backgroundColor(窗口背景颜色,即页面下拉后漏出的背景窗口颜色)、backgroundTextStyle(设置下拉背景字体、loading图的样式,目前只支持dark和light)、navigationBarBackgroundColor(导航栏背景颜色)、navigationBarTextStyle(导航栏标题颜色,目前只支持black和white)、navigationBarTitleText(导航栏标题文字内容)、navigationStyle(值为custom自定义导航栏)
微信小程序设置颜色的时候,只支持十六进制颜色,不支持RGB格式和颜色英文。
  • tarBar属性,用于配置窗口底部的tabBar,其属性值为一个对象,主要有color(设置tab未激活状态文字的颜色)、selectedColor(设置tab激活状态的文字颜色)、borderStyle(设置tabBar上边框的颜色,目前只支持black和white)、backgroundColor(设置tab的背景颜色)、list(用于配置tab项,最多可配置5项),list属性值为一个数组,主要包括text(tab上显示的文字内容)、iconPath(tab处于未激活状态时显示的图标路径)、selectedPath(tab处于激活状态时显示的图标路径)、pagePath(tab被点击时要跳转的页面路径,其属性值为pages中配置的路径)
页面配置配置相对于全局主配置文件来说要简单得多,在页面配置文件中只能配置窗口的样式属性,即只能配置全局配置文件中的window属性中的内容,页面配置文件中配置的内容会覆盖掉全局配置文件中window中相同的配置,以决定当前页面的窗口表现,无需使用window属性,直接将window配置放到花括号中即可

小程序页面Vue生命周期

小程序给页面提供了onLoad(页面加载)、onShow(页面显示,但还未渲染完成)、onReady(页面渲染完成)、onHide(页面隐藏)、onUnload(页面卸载),mpvue将小程序提供的页面生命周期和vue的生命周期结合在了一起,也就是说使用mpvue开发小程序,可以同时使用小程序的生命周期和vue的生命周期,其顺序为: beforeCreate --> created --> onLoad --> onShow --> onReady --> beforeMount --> mounted。即Vue首先实例化然后页面开始加载、显示、渲染,页面渲染完成后Vue实例开始挂载

导航到某个页面
所谓导航到某个页面,就是跳转到某个页面,但是其会保留当前页面,跳转的目的页面导航栏左侧中自带一个返回按钮,点击可以回到之前的页面,但是这个跳转的目的页面不能是tabbar中的页面,其使用的是wx.navigateTo({})

wx.navigateTo({
    url: "../myLesson/main" // 导航到我的课程页面,目标页面自带返回按钮,点击可返回之前的页面
});
Copy after login

动态设置页面导航栏标题
当我们点击列表中的某个具体项时,通常需要在其对应页面动态显示出当前点击项的具体导航栏标题,微信小程序提供了wx.setNavigationBarTitle({})用于动态设置导航栏栏标题,同样有success、fail、complete三个回调函数,如:

wx.setNavigationBarTitle({
     title: "动态标题内容",
     success() {
     },
     fail() {
     },
     complete() {
     }
});
Copy after login

本地缓存数据
微信小程序提供了setStorage({})方法,可以将数据存储在本地缓存中指定的 key 中,除非用户主动删除或因存储空间原因被系统清理,否则数据都一直可用。单个 key 允许存储的最大数据长度为 1MB,所有数据存储上限为 10MB。如:

wx.setStorage({
    key:"key",
    data:"value"
});
Copy after login

同样,微信小程序也提供了getStorage({})方法,用于获取对应key中存储的数据,其还有success、fail、complete三个回调函数,如:

wx.getStorage({
    key: "key",
    success (res) { // 成功获取到对应key中的数据
    },
    fail() { // 未成功获取到对应key中的数据
    },
    complete() { // 获取对应key数据结束,不管成功还是失败都会执行
    }
});
Copy after login
getStorage()和setStorage()方法本身是异步的,但是微信小程序提供了对应的同步方法,即getStorageSync("key")setStorageSync("key", "value");

轮播图组件
微信小程序提供了一个轮播图组件,其中只可放置swiper-item组件,swiper有一些常用的属性,如:

  • indicator-dots: 是否显示面板指示点;
  • autoplay: 是否自动切换;
  • interval: 设置自动切换时间间隔;
  • duration: 滑动动画时长;
  • circular: 是否循环播放;
  • indicator-active-color: 设置当前选中的指示点颜色;
<swiper :indicator-dots="indicatorDots" 
        :autoplay="autoPlay" 
        :interval="interval" 
        :duration="duration" 
        :circular="circular" 
        indicator-active-color="rgba(255,255,255, 0.6)">
        <block v-for="(item, index) in imgUrls" :key="index">
            <swiper-item>
                <img :src="item" class="slide-item"/>
            </swiper-item>
        </block>
</swiper>
Copy after login
当然,组件不仅仅能实现图片的轮播,还可以实现其他轮播,比如列表内容的轮播(导航和内容的联动),我们不给其添加indicator-dots、autoplay、interval、duration、circular等属性,而是通过手进行滑动,swiper组件还有一个current属性,属性值为滑动块的索引值,用于显示对应的滑动item,从而实现导航和内容的联动,即点击导航,自动切换到对应内容。swiper组件也提供了change事件,当我们手动滑动滑动item的时候,就会触发change事件,可以在事件对象中拿到对应滑块的索引,从而更新导航位置,实现滑动内容,自动高亮导航位置

可滚动区域组件
微信提供了一个可滚动区域组件,用于设置该区域中的内容是可以滚动的,通常用于实现可滚动的导航标签栏,其常用属性为:

  • scroll-x: 是否允许横向滚动;
  • scroll-y: 是否允许纵向滚动;
  • scroll-into-view: 属性值为对应滚动item的id,表示自动滚动到对应id元素位置;
  • scroll-with-animation: 在设置滚动条位置时使用动画过渡;
要实现点击某个滚动item后,自动滚动到对应滚动item位置,那么需要给每个滚动item添加一个id,然后动态改变scroll-into-view的值为对应的滚动item的id即可。
<scroll-view class="btns_wrap" 
             scroll-x :scroll-into-view="toChildView" 
             scroll-with-animation>
    <span :class="{active: currentIndex === index}" 
          class="btn_scroll" 
          v-for="(item, index) in allLessons" 
          :key="index" 
          :id="item.id" 
          @click="switchItem(index)">
          {{item.name}}
    </span>
</scroll-view>
Copy after login

本文来自 小程序开发 栏目,欢迎学习!

The above is the detailed content of How does mpvue develop WeChat mini programs? Introduction to basic knowledge. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!