Home  >  Article  >  WeChat Applet  >  Basic knowledge of developing WeChat applet with mpvue

Basic knowledge of developing WeChat applet with mpvue

hzc
hzcforward
2020-06-22 11:26:322915browse

1. Introduction to mpvue

mpvue is a front-end framework that uses Vue.js to develop small programs. The framework is based on the core of Vue.js. mpvue modifies the runtime and compiler implementation 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.

2. Quick Start with mpvue

① Introduce mpvue template through scaffolding

vue 3.0 no longer supports 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
npm run dev command will be generated in the project root directory 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 the WeChat Developer Tools. You also need to apply for a small program ID, that is, AppID, because creates small programs through WeChat Developer Tools. The project needs to fill in the AppID, which can be obtained by applying 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.

3. Some usage details of mpvue

① The src directory of mpvue is the same as vue.

There is also an App.vue root component, App.vue root component is just a structure , has no specific content, the root component has a corresponding main.js file used to render the App.vue root component , that is, introduce App.vue and create a Vue instance as a Vue constructor, then mount, and there is also a app.json file, that is, page global configuration file, Used for page registration, tabBar registration, global window style setting, such as:

// App.vue

3f1c4e4b6b16bbbd69b2ee476dc4f83a

export default {
 
}
2cacc6d41bbb37262a98f745aa00fbf0

c9ccee2e6ea535a969eb3f532ad9fe89
page {
  width: 100%;
  height: 100%;
  background-color: #f7f7f7;
}
531ac245ce3e4fe3d50054a55f265927
// main.js

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

const app = new Vue(App)
app.$mount()
// app.json

{
  "pages": [
    "pages/index/main"
  ],
  "tabBar": {
    ......
  },
  "window": {
    "backgroundColor":"#00BFFF",
    "backgroundTextStyle": "light",
    "navigationBarBackgroundColor": "#fff",
    "navigationBarTitleText": "测试",
    "navigationBarTextStyle": "black"
  }
}
② The pages defined in mpvue are placed in

pages in the src directory In the directory , one page corresponds to one folder , and each page folder needs to have a .vue file and main.js file , main What .js mainly does is, Introduce the .vue corresponding to the current page, then create a Vue instance as a parameter of the Vue constructor and mount, and the name of main.js cannot be changed,It 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()
In mpvue, although the name of the .vue file in a page can be arbitrary,
.js and .json file names are fixed to main . Usually our .vue files also use index.vue. All pages usually contain index.vue, main.js, main. json, distinguishes different pages through outer folders, and in the native applet, different pages are also distinguished through outer folders, but the four in the folder The name of each page can be the same as the outer folder, or it can be different, but the four files must have the same .

Every time a new page is added, you need to restart the project, that is, re-execute npm run dev.

4. WeChat Mini Program Basics and Common API

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

WeChat Mini Program gives us Button
bb9345e55eb71822850ff156dfde57c8 provides some WeChat development capabilities, which expresses by adding an open-type attribute to the bb9345e55eb71822850ff156dfde57c8 tag To give the button the ability type , such as getUserInfo, that is, the ability to click the button to obtain user information, we need to listen to the getuserinfo event on the bb9345e55eb71822850ff156dfde57c8, mpvue It is encapsulated on the basis of the mini program, and user information needs to be obtained through e.mp.detail.userInfo,
1b84c2ef82cb742a2cccf70ca3d50af4点击开始65281c5ac262bf6d81768915a4a77ac0
3f1c4e4b6b16bbbd69b2ee476dc4f83a
export default {
    getUserInfo(e) {
      console.log(e.mp.detail.userInfo); // 获取用户信息
    }
}
2cacc6d41bbb37262a98f745aa00fbf0

wx global object Just like a web page running in a browser environment, the browser environment will provide a global window object. Similarly, a mini program will run in a mini program environment.
The mini program environment will also provide a global wx object, wx will provide many APIs, such as accessing the network (wx.request({})), page jump (wx.redirectTo({})), and display loading ( wx.showLoading({})), display prompts (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
    }
});
需要注意的是,返回状态码为404也算请求成功一般只有网络异常的时候才算请求失败

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

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

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

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

页面配置文件
小程序的页面配置文件分为全局配置文件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" // 导航到我的课程页面,目标页面自带返回按钮,点击可返回之前的页面
});

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

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

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

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

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

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

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

  • indicator-dots: 是否显示面板指示点;
  • autoplay: 是否自动切换;
  • interval: 设置自动切换时间间隔;
  • duration: 滑动动画时长;
  • circular: 是否循环播放;
  • indicator-active-color: 设置当前选中的指示点颜色;
382b563c9fc8b25f4069f27991de6a93
        3e350b609204f318855334b7470a220e
            718137ecd0896f921b876dfd20260138
                1f614e0bc8782717a386429e7848db05
            6b9c44cec84deee6d613a7bf98241fff
        36b196a5d42bcd29e331cb722979f9a6
00d60d359d79ef3ad471162a03ef38f0
当然,806a43c0997cff837bc4d4708cd6ae53组件不仅仅能实现图片的轮播,还可以实现其他轮播,比如列表内容的轮播(导航和内容的联动),我们不给其添加indicator-dots、autoplay、interval、duration、circular等属性,而是通过手进行滑动,swiper组件还有一个current属性,属性值为滑动块的索引值,用于显示对应的滑动item,从而实现导航和内容的联动,即点击导航,自动切换到对应内容。swiper组件也提供了change事件,当我们手动滑动滑动item的时候,就会触发change事件,可以在事件对象中拿到对应滑块的索引,从而更新导航位置,实现滑动内容,自动高亮导航位置

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

  • 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>

推荐教程:《微信小程序

The above is the detailed content of Basic knowledge of developing WeChat applet with mpvue. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete