### Install mpvue-simple Globally
Source: http://mpvue.com/mpvue/simple.html
Install the mpvue-simple tool globally using npm for command-line usage.
```bash
npm i mpvue-simple -g
```
--------------------------------
### mpvueSimple.devServer(argvOptions)
Source: http://mpvue.com/mpvue/simple.html
Starts a development server for the mpvue project.
```APIDOC
## POST mpvueSimple.devServer
### Description
Starts the development server using the provided configuration options.
### Parameters
#### Request Body
- **argvOptions** (object) - Optional - Configuration options for the dev server, including entry, output, and custom config paths.
```
--------------------------------
### Create a Vue Single File Component (SFC)
Source: http://mpvue.com/mpvue/simple.html
Example of creating a basic *.vue SFC file using echo command. This SFC defines a simple template, script with data, and style.
```bash
echo -e '
Hello {{msg}}!
\n\n' > App.vue
```
--------------------------------
### Install mpvue-simple as a Dev Dependency
Source: http://mpvue.com/mpvue/simple.html
Install the mpvue-simple package as a development dependency in your project using npm.
```bash
npm i mpvue-simple --save-dev
```
--------------------------------
### Picker Component Binding in mpvue
Source: http://mpvue.com/mpvue/index.html
Example of using the 'picker' component to replace the 'select' component for form input. It demonstrates how to handle the change event.
```Vue
当前选择:{{array[index]}}
```
--------------------------------
### 小程序 Native Component Event Binding
Source: http://mpvue.com/mpvue/index.html
Demonstrates how to bind events to小程序 (mini-program) native components using Vue's event binding syntax. For example, 'bindchange' becomes '@change'.
```Vue Template
当前选择: {{date}}
```
--------------------------------
### Radio Group Binding in mpvue
Source: http://mpvue.com/mpvue/index.html
Example of using the 'radio-group' component to handle radio button selections. It shows how to bind the change event and manage the radio items.
```Vue
```
--------------------------------
### 初始化 mpvue 项目
Source: http://mpvue.com/mpvue/quickstart.html
通过 vue-cli 使用 mpvue-quickstart 模板创建并启动项目。
```bash
# 1. 先检查下 Node.js 是否安装成功
$ node -v
v8.9.0
$ npm -v
5.6.0
# 2. 由于众所周知的原因,可以考虑切换源为 taobao 源
$ npm set registry https://registry.npm.taobao.org/
# 3. 全局安装 vue-cli
# 一般是要 sudo 权限的
$ npm install --global vue-cli@2.9
# 4. 创建一个基于 mpvue-quickstart 模板的新项目
# 新手一路回车选择默认就可以了
$ vue init mpvue/mpvue-quickstart my-project
# 5. 安装依赖,走你
$ cd my-project
$ npm install
$ npm run dev
```
--------------------------------
### mpvueSimple.build(argvOptions)
Source: http://mpvue.com/mpvue/simple.html
Builds the project for a single page or component based on provided options.
```APIDOC
## POST mpvueSimple.build
### Description
Builds the project for a single page or component. Returns a Promise that resolves on success.
### Parameters
#### Request Body
- **build** (boolean) - Optional - Build production code switch.
- **component** (boolean) - Optional - If true, compiles as a custom Component; otherwise defaults to Page level.
- **entry** (string) - Optional - Entry file path.
- **output** (string) - Optional - Output directory for compiled code.
- **pageName** (string) - Optional - Name of the generated小程序 page folder and file.
- **config** (string) - Optional - Path to a custom webpack config file to be injected.
### Response
#### Success Response (200)
- **Promise** (object) - Resolves when the build process completes successfully.
```
--------------------------------
### 快速启动 mpvue 项目
Source: http://mpvue.com/build/index.html
使用 vue-cli 快速初始化并启动一个 mpvue 项目。
```bash
# 全局安装 vue-cli
$ npm install --global vue-cli
# 创建一个基于 mpvue-quickstart 模板的新项目
$ vue init mpvue/mpvue-quickstart my-project
# 安装依赖,走你
$ cd my-project
$ npm install
$ npm run dev
```
--------------------------------
### 初始化 mpvue 项目
Source: http://mpvue.com/mpvue/index.html
使用 vue-cli 快速创建并启动一个 mpvue 小程序项目。
```bash
# 全局安装 vue-cli
$ npm install --global vue-cli
# 创建一个基于 mpvue-quickstart 模板的新项目
$ vue init mpvue/mpvue-quickstart my-project
# 安装依赖
$ cd my-project
$ npm install
# 启动构建
$ npm run dev
```
--------------------------------
### Define app.json Configuration
Source: http://mpvue.com/change-log/2018.7.24.html
Defines the application pages and window settings in the new app.json file.
```json
+{
+ "pages": [
+ "pages/index/main",
+ "pages/counter/main",
+ "pages/logs/main"
+ ],
+ "window": {
+ "backgroundTextStyle": "light",
+ "navigationBarBackgroundColor": "#fff",
+ "navigationBarTitleText": "WeChat",
+ "navigationBarTextStyle": "black"
+ }
+}
```
--------------------------------
### Run mpvue-lint syntax check
Source: http://mpvue.com/build/mpvue-lint.html
Use the build method to check a list of entry Vue files for syntax compatibility with mpvue.
```javascript
const mpvueLint = require('mpvue-lint')
mpvueLint.build(
{
entry:
[
path.resolve('mpvue/page/worldcup/home/index.vue'),
path.resolve('mpvue/page/worldcup/card_detail/index.vue'),
path.resolve('mpvue/page/worldcup/activity_rules/index.vue')
]
})
```
--------------------------------
### Mpvue Application Entry Point with TypeScript
Source: http://mpvue.com/build/mpvue-loader.html
Sets up the main entry point for a Mpvue application using TypeScript. It registers Mpvue-specific hooks and initializes the Vue application instance.
```typescript
// main.ts
import { Component, Emit, Inject, Model, Prop, Provide, Vue, Watch } from 'vue-property-decorator';
import { VueConstructor } from "vue";
interface IMpVue extends VueConstructor {
mpType: string
}
// 添加小程序hooks http://mpvue.com/mpvue/#_4
Component.registerHooks([
// app
'onLaunch', // 初始化
'onShow', // 当小程序启动,或从后台进入前台显示
'onHide', // 当小程序从前台进入后台
// pages
'onLoad', // 监听页面加载
'onShow', // 监听页面显示
'onReady', // 监听页面初次渲染完成
'onHide', // 监听页面隐藏
'onUnload', // 监听页面卸载
'onPullDownRefresh', // 监听用户下拉动作
'onReachBottom', // 页面上拉触底事件的处理函数
'onShareAppMessage', // 用户点击右上角分享
'onPageScroll', // 页面滚动
'onTabItemTap', //当前是 tab 页时, 点击 tab 时触发 (mpvue 0.0.16 支持)
])
Vue.config.productionTip = false
// 在这个地方引入是为了registerHooks先执行
const MyApp = require('./App.vue').default as IMpVue
const app = new Vue(MyApp)
app.$mount()
```
--------------------------------
### Build Single Page with Custom Options CLI
Source: http://mpvue.com/mpvue/simple.html
Build a single Page-level mini-program page with custom options using the mpvue-simple CLI. Specify entry point, output directory, page name, and webpack configuration.
```bash
mpvue-simple --build --entry ./src/login.vue --output ./mp-pages/ --pageName login --config ./build/webpack.page.js
```
--------------------------------
### Build a Single Page with mpvue-simple CLI
Source: http://mpvue.com/mpvue/simple.html
Build a single Page-level mini-program page using the mpvue-simple command-line interface. This command initiates the build process for the current project.
```bash
mpvue-simple --build
```
--------------------------------
### 配置 webpack 构建目标
Source: http://mpvue.com/build/index.html
将 webpack target 设置为 mpvue-webpack-target 以适配微信小程序。
```javascript
{
// ...
entry: {
// ...
},
target: require('mpvue-webpack-target') // 改这里
}
```
--------------------------------
### 配置 postcss-mpvue-wxss 插件
Source: http://mpvue.com/build/index.html
配置 postcss 插件以转换样式规范至微信小程序 wxss。
```javascript
{
vue: {
loaders: utils.cssLoaders(),
postcss: [
// ...
require('postcss-mpvue-wxss')
]
},
}
```
```javascript
// https://github.com/michael-ciniawsky/postcss-load-config
module.exports = {
"plugins": {
// to edit target browsers: use "browserslist" field in package.json
"autoprefixer": {},
"postcss-mpvue-wxss": {}
}
}
```
--------------------------------
### 配置 mpvue-loader 处理 Vue 文件
Source: http://mpvue.com/build/index.html
在 webpack 规则中将 vue-loader 替换为 mpvue-loader。
```javascript
{
// ...
module: {
rules: [
// ...
{
test: /\.vue$/,
loader: 'mpvue-loader', // 改这里
options: vueLoaderConfig
},
]
}
}
```
--------------------------------
### 配置 mpvue-loader 处理 JS 文件
Source: http://mpvue.com/build/index.html
为 JS 文件添加 mpvue-loader 以支持小程序入口检查。
```javascript
{
// ...
module: {
rules: [
// ...
{
test: /\.js$/,
include: [resolve('src'), resolve('test')],
use: [ // 改这里
'babel-loader',
{
loader: 'mpvue-loader',
options: {
checkMPEntry: true
}
},
]
},
]
}
}
```
--------------------------------
### Initialize mpvue-trace memory check
Source: http://mpvue.com/build/mpvue-lint.html
Inject the trace method into the page's main.js to monitor data update sizes. Ensure this is removed before deploying to production as it impacts performance.
```javascript
const mpvueTrace = require('mpvue-lint/mpvue-trace')
mpvueTrace.trace(Vue); //Vue是当前页面中的Vue实例
```
--------------------------------
### 更新 webpack.base.conf.js 配置
Source: http://mpvue.com/change-log/2018.7.24.html
更新入口解析逻辑并添加 CopyWebpackPlugin 以支持 main.json 和静态资源处理。
```javascript
// build/webpack.base.conf.js
+var CopyWebpackPlugin = require('copy-webpack-plugin')
+var relative = require('relative')
function resolve (dir) {
return path.join(__dirname, '..', dir)
}
-function getEntry (rootSrc, pattern) {
- var files = glob.sync(path.resolve(rootSrc, pattern))
- return files.reduce((res, file) => {
- var info = path.parse(file)
- var key = info.dir.slice(rootSrc.length + 1) + '/' + info.name
- res[key] = path.resolve(file)
- return res
- }, {})
+function getEntry (rootSrc) {
+ var map = {};
+ glob.sync(rootSrc + '/pages/**/main.js')
+ .forEach(file => {
+ var key = relative(rootSrc, file).replace('.js', '');
+ map[key] = file;
+ })
+ return map;
}
const appEntry = { app: resolve('./src/main.js') }
const pagesEntry = getEntry(resolve('./src'), 'pages/**/main.js')
const entry = Object.assign({}, appEntry, pagesEntry)
@@ -108,6 +122,14 @@ module.exports = {
]
},
plugins: [
- new MpvuePlugin()
+ new MpvuePlugin(),
+ new CopyWebpackPlugin([{
+ from: '**/*.json',
+ to: ''
+ }], {
+ context: 'src/'
+ })
+ new CopyWebpackPlugin([ // 处理 main.json 里面引用的图片,不要放代码中引用的图片
+ {
+ from: path.resolve(__dirname, '../static'),
+ to: path.resolve(__dirname, '../dist/static'),
+ ignore: ['.*']
+ }
+ ])
]
}
```
--------------------------------
### 安装 mpvue 项目依赖
Source: http://mpvue.com/build/index.html
安装 mpvue 核心库及相关构建工具依赖。
```bash
npm i mpvue -S
npm i mpvue-template-compiler mpvue-loader mpvue-webpack-target postcss-mpvue-wxss webpack-dev-middleware-hard-disk -S-D
```
--------------------------------
### 捕获小程序 App 错误
Source: http://mpvue.com/qa.html
在 App 根组件中定义 onError 回调函数以捕获应用运行时的错误。
```javascript
export default {
// 只有 app 才会有 onLaunch 的生命周期
onLaunch () {
// ...
},
// 捕获 app error
onError (err) {
console.log(err)
}
}
```
--------------------------------
### Build Single Page with Options Node.js API
Source: http://mpvue.com/mpvue/simple.html
Build a single Page-level mini-program page with specified output directory and page name using the mpvue-simple Node.js API.
```javascript
mpvueSimple.build({
output: 'mp-pages',
pageName: 'login'
})
```
--------------------------------
### Build with Promise Handling Node.js API
Source: http://mpvue.com/mpvue/simple.html
Build a single Page-level mini-program page using the mpvue-simple Node.js API and handle the Promise returned for success or error.
```javascript
mpvueSimple.build() // => Promise
.then(() => console.log('mpvue build success'))
.catch(err => throw new Error(err))
```
--------------------------------
### mpvueSimple.getWebpackConfig()
Source: http://mpvue.com/mpvue/simple.html
Retrieves the current webpack configuration used for production builds.
```APIDOC
## GET mpvueSimple.getWebpackConfig
### Description
Returns the webpack configuration object used for building the project.
```
--------------------------------
### mpvueSimple.getDevWebpackConfig()
Source: http://mpvue.com/mpvue/simple.html
Retrieves the webpack configuration used for the development server.
```APIDOC
## GET mpvueSimple.getDevWebpackConfig
### Description
Returns the webpack configuration object used for the development environment.
```
--------------------------------
### 配置 webpack 入口
Source: http://mpvue.com/build/index.html
定义项目入口,app 字段会被识别为小程序 app 类型。
```javascript
{
// ...
entry: {
app: resolve('./src/main.js'), // app 字段被识别为 app 类型
'list/main': resolve('./src/pages/list/main.js'), // 其余字段被识别为 page 类型
'page1/main': resolve('./src/pages/page1/main.js')
}
}
```
--------------------------------
### 更新 webpack.dev.conf.js 输出路径
Source: http://mpvue.com/change-log/2018.7.24.html
修改生成文件的输出路径,使其符合新的目录结构要求。
```javascript
module.exports = merge(baseWebpackConfig, {
devtool: '#source-map',
output: {
path: config.build.assetsRoot,
- filename: utils.assetsPath('js/[name].js'),
- chunkFilename: utils.assetsPath('js/[id].js')
+ filename: utils.assetsPath('[name].js'),
+ chunkFilename: utils.assetsPath('[id].js')
},
plugins: [
new webpack.DefinePlugin({
@@ -42,8 +42,8 @@ module.exports = merge(baseWebpackConfig, {
// copy from ./webpack.prod.conf.js
// extract css into its own file
new ExtractTextPlugin({
- filename: utils.assetsPath('css/[name].wxss')
+ filename: utils.assetsPath('[name].wxss')
}),
@@ -53,7 +53,7 @@ module.exports = merge(baseWebpackConfig, {
}
}),
new webpack.optimize.CommonsChunkPlugin({
- name: 'vendor',
+ name: 'common/vendor',
minChunks: function (module, count) {
// any required modules inside node_modules are extracted to vendor
return (
@@ -64,17 +64,9 @@ module.exports = merge(baseWebpackConfig, {
}
}),
new webpack.optimize.CommonsChunkPlugin({
- name: 'manifest',
- chunks: ['vendor']
+ name: 'common/manifest',
+ chunks: ['common/vendor']
}),
- // copy custom static assets
- new CopyWebpackPlugin([
- {
- from: path.resolve(__dirname, '../static'),
- to: config.build.assetsSubDirectory,
- ignore: ['.*']
- }
- ]),
```
--------------------------------
### Configure Webpack Entry for mpvue
Source: http://mpvue.com/build/mpvue-loader.html
Define entry points in webpack.config.js. The 'app' field is recognized as the application entry, while others are treated as page entries.
```javascript
// webpack.config.js
{
// ...
entry: {
app: resolve('./src/main.js'), // app 字段被识别为 app 类型
index: resolve('./src/pages/index/main.js'), // 其余字段被识别为 page 类型
'news/home': resolve('./src/pages/news/home/index.js')
}
}
```
--------------------------------
### Exporting Configuration from Entry File
Source: http://mpvue.com/build/mpvue-loader.html
Export a 'config' object from your main entry file (e.g., main.js) to define app.json or page.json settings for older mpvue versions.
```javascript
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'
}
}
};
```
--------------------------------
### Build Single Page with Node.js API
Source: http://mpvue.com/mpvue/simple.html
Build a single Page-level mini-program page using the mpvue-simple Node.js API. This is a basic build call.
```javascript
const mpvueSimple = require('mpvue-simple')
// build for signel Page
mpvueSimple.build()
```
--------------------------------
### Configure Hot Updates with webpack-dev-middleware-hard-disk
Source: http://mpvue.com/build
Set up hot module replacement by using webpack-dev-middleware-hard-disk to map cached files to disk, enabling the WeChat mini program's auto-refresh functionality. This code should be placed in a file similar to webpack/dev-server.js.
```javascript
var config = require('./config')
if (!process.env.NODE_ENV) {
process.env.NODE_ENV = JSON.parse(config.dev.env.NODE_ENV)
}
var path = require('path')
var webpack = require('webpack')
var webpackConfig = require('./webpack.dev.conf')
var compiler = webpack(webpackConfig)
require('webpack-dev-middleware-hard-disk')(compiler, {
publicPath: webpackConfig.output.publicPath,
quiet: true
})
```
--------------------------------
### Class 绑定语法转换
Source: http://mpvue.com/mpvue/index.html
展示 mpvue 中 Class 绑定语法的编写方式及其对应的编译转换结果。
```html
111
222
333
444
555
```
```html
111222333444555
```
--------------------------------
### Update Build Configuration
Source: http://mpvue.com/change-log/2018.7.24.html
Modifies the assetsSubDirectory to empty string to change how resources are aggregated.
```javascript
module.exports = {
env: require('./prod.env'),
index: path.resolve(__dirname, '../dist/index.html'),
assetsRoot: path.resolve(__dirname, '../dist'),
- assetsSubDirectory: 'static', // 不将资源聚合放在 static 目录下
+ assetsSubDirectory: '',
assetsPublicPath: '/',
productionSourceMap: false,
// Gzip off by default as many popular static hosts such as
@@ -26,7 +26,7 @@ module.exports = {
port: 8080,
// 在小程序开发者工具中不需要自动打开浏览器
autoOpenBrowser: false,
- assetsSubDirectory: 'static', // 不将资源聚合放在 static 目录下
+ assetsSubDirectory: '',
assetsPublicPath: '/',
proxyTable: {},
// CSS Sourcemaps off by default because relative paths are "buggy"
```
--------------------------------
### Style 绑定语法转换
Source: http://mpvue.com/mpvue/index.html
展示 mpvue 中 Style 绑定语法的编写方式及其对应的编译转换结果。
```html
666
777
```
```html
666777
```
--------------------------------
### Event Mapping in mpvue
Source: http://mpvue.com/mpvue/index.html
This object maps standard web events to their corresponding小程序 (mini-program) events. Use this for event handling in mpvue.
```JavaScript
{
click: 'tap',
touchstart: 'touchstart',
touchmove: 'touchmove',
touchcancel: 'touchcancel',
touchend: 'touchend',
tap: 'tap',
longtap: 'longtap',
input: 'input',
change: 'change',
submit: 'submit',
blur: 'blur',
focus: 'focus',
reset: 'reset',
confirm: 'confirm',
columnchange: 'columnchange',
linechange: 'linechange',
error: 'error',
scrolltoupper: 'scrolltoupper',
scrolltolower: 'scrolltolower',
scroll: 'scroll'
}
```
--------------------------------
### Configure NODE_ENV Environment Variable
Source: http://mpvue.com/build/index.html
Sets the environment to production to manage error reporting levels and wxss generation.
```javascript
process.env.NODE_ENV = 'production'
```
--------------------------------
### 定义 Vue 实例与生命周期
Source: http://mpvue.com/mpvue/index.html
展示如何在 mpvue 中定义 Vue 实例,并同时使用 Vue 和小程序特有的生命周期钩子。
```javascript
new Vue({
data: {
a: 1
},
created () {
// `this` 指向 vm 实例
console.log('a is: ' + this.a)
},
onShow () {
// `this` 指向 vm 实例
console.log('a is: ' + this.a, '小程序触发的 onshow')
}
})
// => "a is: 1"
```
--------------------------------
### Update Webpack Production Configuration
Source: http://mpvue.com/change-log/2018.7.24.html
Adjusts output paths, CSS extraction, and CommonsChunkPlugin settings for MPVue production builds.
```javascript
@@ -24,10 +24,10 @@ var webpackConfig = merge(baseWebpackConfig, {
devtool: config.build.productionSourceMap ? '#source-map' : false,
output: {
path: config.build.assetsRoot,
- filename: utils.assetsPath('js/[name].js'),
- chunkFilename: utils.assetsPath('js/[id].js')
+ filename: utils.assetsPath('[name].js'),
+ chunkFilename: utils.assetsPath('[id].js')
},
plugins: [
// http://vuejs.github.io/vue-loader/en/workflow/production.html
@@ -39,8 +39,8 @@ var webpackConfig = merge(baseWebpackConfig, {
}),
// extract css into its own file
new ExtractTextPlugin({
- // filename: utils.assetsPath('css/[name].[contenthash].css')
- filename: utils.assetsPath('css/[name].wxss')
+ // filename: utils.assetsPath('[name].[contenthash].css')
+ filename: utils.assetsPath('[name].wxss')
}),
// Compress extracted CSS. We are using this plugin so that possible
// duplicated CSS from different components can be deduped.
@@ -72,7 +72,7 @@ var webpackConfig = merge(baseWebpackConfig, {
new webpack.HashedModuleIdsPlugin(),
// split vendor js into its own file
new webpack.optimize.CommonsChunkPlugin({
- name: 'vendor',
+ name: 'common/vendor',
minChunks: function (module, count) {
// any required modules inside node_modules are extracted to vendor
return (
@@ -85,17 +85,9 @@ var webpackConfig = merge(baseWebpackConfig, {
// extract webpack runtime and module manifest to its own file in order to
// prevent vendor hash from being updated whenever app bundle is updated
new webpack.optimize.CommonsChunkPlugin({
- name: 'manifest',
- chunks: ['vendor']
- }),
+ name: 'common/manifest',
+ chunks: ['common/vendor']
+ })
- // copy custom static assets
- new CopyWebpackPlugin([
- {
- from: path.resolve(__dirname, '../static'),
- to: config.build.assetsSubDirectory,
- ignore: ['.*']
- }
- ])
]
})
```
--------------------------------
### Mpvue Page Component with TypeScript
Source: http://mpvue.com/build/mpvue-loader.html
Implements a page component in Mpvue using TypeScript and decorators. It demonstrates importing and registering child components like Card and CompB.
```typescript
// index.ts
import { Vue, Component } from 'vue-property-decorator'
import Card from '@/components/card.vue' // mpvue目前只支持的单文件组件
import CompB from '@/components/compb.vue' // mpvue目前只支持的单文件组件
// 必须使用装饰器的方式来指定component
@Component({
components: {
Card,
CompB, //注意,vue的组件在template中的用法,`CompB` 会被转成 `comp-b`
},
})
class Index extends Vue {
ver: number = 123
onShow() { // 小程序 hook
}
mounted() { // vue hook
}
}
export default Index
```
--------------------------------
### Scoped Style Transformation in mpvue
Source: http://mpvue.com/build/mpvue-loader.html
Demonstrates how mpvue-loader modifies scoped styles by appending the module-id to class names directly, unlike vue-loader which uses attribute selectors.
```html
// ...
// ...
// ...
```
--------------------------------
### Implement Hot Reloading with webpack-dev-middleware-hard-disk
Source: http://mpvue.com/build/index.html
Configures the development server to map memory-cached files to the hard disk, enabling automatic refreshes in the WeChat DevTools.
```javascript
var config = require('./config')
if (!process.env.NODE_ENV) {
process.env.NODE_ENV = JSON.parse(config.dev.env.NODE_ENV)
}
var path = require('path')
var webpack = require('webpack')
var webpackConfig = require('./webpack.dev.conf')
var compiler = webpack(webpackConfig)
require('webpack-dev-middleware-hard-disk')(compiler, {
publicPath: webpackConfig.output.publicPath,
quiet: true
})
```
--------------------------------
### 配置 resolve alias
Source: http://mpvue.com/build/index.html
将 vue 别名指向 mpvue 运行时以保持兼容性。
```javascript
{
resolve: {
// ...
alias: {
'vue': 'mpvue',
// ...
}
}
}
```
--------------------------------
### Configure Webpack Loaders for Mpvue and TypeScript
Source: http://mpvue.com/build/mpvue-loader.html
This webpack configuration adds 'mpvue-loader' and 'awesome-typescript-loader' to handle .vue and .tsx files, enabling TypeScript support within Mpvue.
```javascript
// webpack.conf.js
module.exports = {
//...
module: {
rules: [
{
test: /\.vue$/,
loader: 'mpvue-loader',
options: {
//...
ts: [ //添加对应vue的loader
'babel-loader',
{
// loader: 'ts-loader',
loader: 'awesome-typescript-loader',
options: {
// errorsAsWarnings: true,
useCache: true,
}
}
]
}
},
// ts文件的loader
{
test: /\.tsx?$/,
exclude: /node_modules/,
use: [
'babel-loader',
{
loader: 'mpvue-loader',
options: {
checkMPEntry: true
}
},
{
// loader: 'ts-loader',
loader: 'awesome-typescript-loader',
options: {
// errorsAsWarnings: true,
useCache: true,
}
}
]
},
]
// ...
}
```
--------------------------------
### Mpvue App Component with TypeScript
Source: http://mpvue.com/build/mpvue-loader.html
Defines the root App component for a Mpvue application using TypeScript and decorators. It includes Mpvue lifecycle hooks like onLaunch, onShow, and onHide.
```typescript
//app.ts
import { Vue, Component } from 'vue-property-decorator'
declare module "vue/types/vue" {
interface Vue {
$mp: any;
}
}
// 必须使用装饰器的方式来指定components
@Component({
mpType: 'app', // mpvue特定
}as any)
class App extends Vue {
// app hook
onLaunch() {
let opt = this.$root.$mp.appOptions
}
onShow() {
}
onHide() {
}
mounted() { // vue hook
}
}
export default App
```
--------------------------------
### 模板语法限制示例
Source: http://mpvue.com/mpvue/index.html
展示模板中不支持的复杂 JS 表达式以及在事件处理函数中支持的用法。
```html
{{ message.split('').reverse().join('') }}
{{ item.value }}
```
--------------------------------
### Set NODE_ENV to Production
Source: http://mpvue.com/build
Configure the NODE_ENV environment variable to 'production'. This is a simple way to manage environment settings, affecting build output such as whether to generate separate wxss files.
```javascript
process.env.NODE_ENV = 'production'
```
--------------------------------
### Mpvue Card Component with TypeScript
Source: http://mpvue.com/build/mpvue-loader.html
A reusable Card component for Mpvue implemented in TypeScript. It uses the @Prop decorator to define a reactive 'text' property and includes Mpvue lifecycle hooks.
```typescript
// card.ts
import { Vue, Component, Prop } from 'vue-property-decorator'
// 必须使用装饰器的方式来指定component
@Component
class Card extends Vue {
@Prop({ default: '1' }) //注意用法!
text: string;
ver: number = 2;
onShow() {
}
onHide() {
}
mounted() { // vue hook
}
}
export default CompB
```
--------------------------------
### Remove Configuration from main.js
Source: http://mpvue.com/change-log/2018.7.24.html
Removes the config object from the main.js file as it is being migrated to app.json.
```javascript
-export default {
- // 这个字段走 app.json
- config: {
- // 页面前带有 ^ 符号的,会被编译成首页,其他页面可以选填,我们会自动把 webpack entry 里面的入口页面加进去
- pages: ['pages/logs/main', '^pages/index/main'],
- window: {
- backgroundTextStyle: 'light',
- navigationBarBackgroundColor: '#fff',
- navigationBarTitleText: 'WeChat',
- navigationBarTextStyle: 'black'
- }
- }
-}
```
--------------------------------
### Add Global Whitelist to ESLint Configuration
Source: http://mpvue.com/build
Extend your .eslintrc.js configuration to include a global whitelist for specific variables. This prevents ESLint from flagging these globally available variables as undefined.
```javascript
{
// ...
globals: {
App: true,
Page: true,
wx: true,
getApp: true,
getPage: true
}
}
```
--------------------------------
### Vue Component for WeChat Mini Program
Source: http://mpvue.com/build/mpvue-loader.html
A Vue component template that will be transformed into WXML. It includes data binding and component composition.
```vue
{{msg}}
```
--------------------------------
### Add Global Variables to .eslintrc.js
Source: http://mpvue.com/build/index.html
Defines global WeChat Mini Program objects in the ESLint configuration to prevent undefined variable errors.
```json
{
// ...
globals: {
App: true,
Page: true,
wx: true,
getApp: true,
getPage: true
}
}
```
--------------------------------
### Capture App Errors in Mpvue
Source: http://mpvue.com/mpvue/index.html
Implement an onError callback function on the app's root component to capture and log errors. This is a method for error capturing, not a full lifecycle.
```javascript
export default {
// Only app has onLaunch lifecycle
onLaunch () {
// ...
},
// Capture app error
onError (err) {
console.log(err)
}
}
```
--------------------------------
### 使用 computed 生成 Class
Source: http://mpvue.com/mpvue/index.html
展示通过 computed 属性生成 Class 字符串的推荐做法,以及不支持对象语法的示例。
```html
```
--------------------------------
### Transformed WXML Template
Source: http://mpvue.com/build/mpvue-loader.html
The WXML output generated from a Vue component. It uses template imports and conditional rendering for child components.
```wxml
{{msg}}
```
--------------------------------
### Nested List Rendering in Vue Template
Source: http://mpvue.com/mpvue/index.html
When using nested v-for loops, ensure that different index aliases are specified for each loop to avoid conflicts. This is crucial for correct rendering in mpvue.
```Vue Template
{{item.value}}
```
--------------------------------
### Vue Component Data Structure for mpvue
Source: http://mpvue.com/build/mpvue-loader.html
The tree-like data structure used by mpvue at runtime to manage component instances and pass data via setData.
```json
// 这儿数据结构是一个数组,index 是动态的
{
$child: {
'0':{
// ... root data
$child: {
'0': {
// ... data
msg: 'Hello Vue.js!',
$child: {
// ...data
}
}
}
}
}
}
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.