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.
① 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 templatenpm run dev command will be generated in the project root directory A dist directory, which isnpm install -g @vue/cli-init vue init mpvue/mpvue-quickstart my-project cd my-project npm install npm run devCopy after login
Convert the vue project into a WeChat applet project② Build a development environment for the appletWeChat 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 projectStart 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.
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<script> export default { } </script> <style> page { width: 100%; height: 100%; background-color: #f7f7f7; } </style>
import Vue from 'vue' import App from './App' Vue.config.productionTip = false App.mpType = 'app' const app = new Vue(App) app.$mount()
{ "pages": [ "pages/index/main" ], "tabBar": { ...... }, "window": { "backgroundColor":"#00BFFF", "backgroundTextStyle": "light", "navigationBarBackgroundColor": "#fff", "navigationBarTitleText": "测试", "navigationBarTextStyle": "black" } }
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.jsimport 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()
.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.
① Click the button to prompt the user whether to authorize and obtain user information
WeChat Mini Program gives us Button②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对象,如:
微信小程序设置颜色的时候,只支持十六进制颜色,不支持RGB格式和颜色英文。
页面配置配置相对于全局主配置文件来说要简单得多,在页面配置文件中只能配置窗口的样式属性,即只能配置全局配置文件中的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");
⑪ 轮播图组件
微信小程序提供了一个
<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>
当然,组件不仅仅能实现图片的轮播,还可以实现其他轮播,比如列表内容的轮播(导航和内容的联动),我们不给其添加indicator-dots、autoplay、interval、duration、circular等属性,而是通过手进行滑动,swiper组件还有一个current属性,属性值为滑动块的索引值,用于显示对应的滑动item,从而实现导航和内容的联动,即点击导航,自动切换到对应内容。swiper组件也提供了change事件,当我们手动滑动滑动item的时候,就会触发change事件,可以在事件对象中拿到对应滑块的索引,从而更新导航位置,实现滑动内容,自动高亮导航位置。
⑫ 可滚动区域组件
微信提供了一个
要实现点击某个滚动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!