```
--------------------------------
### Compile Vue Templates to Mini-Program Formats with mpvue-template-compiler
Source: https://context7.com/meituan-dianping/mpvue/llms.txt
This snippet demonstrates how to use the mpvue-template-compiler to convert Vue templates into formats compatible with various mini-program platforms like WeChat (wx), Baidu (swan), Toutiao (tt), and Alipay (my). It shows the compilation process and the resulting render functions and platform-specific MPML code.
```javascript
const compiler = require('mpvue-template-compiler')
const template = `
{{ item.name }}
`
const { render, staticRenderFns, errors } = compiler.compile(template, {
preserveWhitespace: false,
modules: []
})
if (errors.length) {
console.error('编译错误:', errors)
} else {
console.log('渲染函数:', render)
console.log('静态渲染函数:', staticRenderFns)
}
const { compileToMPML } = require('mpvue-template-compiler')
const wxmlCode = compileToMPML(compiled, options, { platform: 'wx' })
const swanCode = compileToMPML(compiled, options, { platform: 'swan' })
const ttCode = compileToMPML(compiled, options, { platform: 'tt' })
const axmlCode = compileToMPML(compiled, options, { platform: 'my' })
```
--------------------------------
### Set Production Environment Variables for Bundlers
Source: https://github.com/meituan-dianping/mpvue/blob/master/dist/README.md
Techniques for replacing process.env.NODE_ENV with 'production' string literals to enable production-only optimizations and code stripping in final bundles.
```javascript
var webpack = require('webpack')
module.exports = {
plugins: [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production')
}
})
]
}
```
```javascript
const replace = require('rollup-plugin-replace')
rollup({
plugins: [
replace({
'process.env.NODE_ENV': JSON.stringify('production')
})
]
})
```
```bash
NODE_ENV=production browserify -g envify -e main.js | uglifyjs -c -m > build.js
```
--------------------------------
### Configure Vuex Store for mpvue
Source: https://context7.com/meituan-dianping/mpvue/llms.txt
Defines the central store using Vuex, including state, getters, mutations for local storage synchronization, and asynchronous actions for API interactions like login and user profile fetching.
```javascript
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: { userInfo: null, token: '', cart: [], systemInfo: {} },
getters: {
isLoggedIn: state => !!state.token,
cartCount: state => state.cart.reduce((sum, item) => sum + item.quantity, 0),
cartTotal: state => state.cart.reduce((sum, item) => sum + item.price * item.quantity, 0)
},
mutations: {
SET_USER_INFO(state, userInfo) { state.userInfo = userInfo },
SET_TOKEN(state, token) { state.token = token; wx.setStorageSync('token', token) },
ADD_TO_CART(state, product) {
const existing = state.cart.find(item => item.id === product.id)
if (existing) existing.quantity++
else state.cart.push({ ...product, quantity: 1 })
},
CLEAR_CART(state) { state.cart = [] },
SET_SYSTEM_INFO(state, info) { state.systemInfo = info }
},
actions: {
async login({ commit }, { code }) {
const res = await new Promise((resolve, reject) => {
wx.request({ url: 'https://api.example.com/login', method: 'POST', data: { code }, success: resolve, fail: reject })
})
commit('SET_TOKEN', res.data.token)
commit('SET_USER_INFO', res.data.userInfo)
return res.data
},
async initApp({ commit, dispatch }) {
const systemInfo = wx.getSystemInfoSync()
commit('SET_SYSTEM_INFO', systemInfo)
const token = wx.getStorageSync('token')
if (token) { commit('SET_TOKEN', token); await dispatch('fetchUserInfo') }
}
}
})
export default store
```
--------------------------------
### Vue.js App Initialization and Animation Loop
Source: https://github.com/meituan-dianping/mpvue/blob/master/benchmarks/svg/index.html
Initializes a Vue instance to manage the application state, including the model for SVG dots and an optimization flag. It sets up a requestAnimationFrame loop to continuously update the model's state and re-render the SVG elements. The optimization toggle allows switching between standard updates and using Object.freeze for performance.
```javascript
var stats = new Stats()
stats.setMode(0)
stats.domElement.style.position = 'absolute'
stats.domElement.style.right = '0px'
stats.domElement.style.top = '0px'
document.body.appendChild(stats.domElement)
var WIDTH = 800
var HEIGHT = 600
new Vue({
el: '#app',
data: {
model: createModel(1000),
optimized: false
},
created: function () {
var self = this
requestAnimationFrame(render)
stats.begin()
function render () {
stats.end()
stats.begin()
requestAnimationFrame(render)
self.model.step()
if (self.optimized) {
self.$forceUpdate()
}
}
},
methods: {
toggleOptimization: function () {
this.model = this.optimized ? createModel(1000) : Object.freeze(createModel(1000))
this.optimized = !this.optimized
}
}
});
```
--------------------------------
### Require vue-template-compiler
Source: https://github.com/meituan-dianping/mpvue/blob/master/packages/vue-template-compiler/README.md
How to import the vue-template-compiler package in a JavaScript project.
```javascript
const compiler = require('vue-template-compiler')
```
--------------------------------
### compiler.compile
Source: https://github.com/meituan-dianping/mpvue/blob/master/packages/vue-template-compiler/README.md
Compiles a template string into JavaScript render function code.
```APIDOC
## POST compiler.compile
### Description
Compiles a template string and returns compiled JavaScript code including the AST, render function, and static render functions.
### Method
POST
### Endpoint
compiler.compile(template, [options])
### Parameters
#### Request Body
- **template** (string) - Required - The template string to compile.
- **options** (object) - Optional - Configuration object including modules, directives, and preserveWhitespace.
### Request Example
{
"template": "
{{ message }}
",
"options": { "preserveWhitespace": false }
}
### Response
#### Success Response (200)
- **ast** (object) - Parsed template elements to AST.
- **render** (string) - Main render function code.
- **staticRenderFns** (array) - Render code for static sub trees.
- **errors** (array) - Template syntax errors, if any.
#### Response Example
{
"render": "with(this){return _c('div',[_v(_s(message))])}",
"staticRenderFns": [],
"errors": []
}
```
--------------------------------
### Parse Single-File Component (SFC)
Source: https://github.com/meituan-dianping/mpvue/blob/master/packages/vue-template-compiler/README.md
Parses a Single-File Component (`.vue` file) into a descriptor object. This is utilized by SFC build tools like `vue-loader` and `vueify` to extract template, script, and style blocks. The `pad` option can be used to align line/character counts for pre-processors.
```javascript
const compiler = require('vue-template-compiler')
const descriptor = compiler.parseComponent(fileContent, {
pad: 'line' // or 'space', useful for pre-processors
})
// descriptor object contains:
// template: SFCBlock | null
// script: SFCBlock | null
// styles: Array
// customBlocks: Array
// errors: Array
```
--------------------------------
### Compile Vue Template to Render Functions
Source: https://github.com/meituan-dianping/mpvue/blob/master/packages/vue-template-compiler/README.md
Compiles a Vue template string directly into instantiated JavaScript render and static render functions. This method uses `new Function()` and is not CSP-compliant. It does not accept compile-time options and is intended for runtime use with pre-configured builds.
```javascript
const compiler = require('vue-template-compiler')
const { render, staticRenderFns } = compiler.compileToFunctions(template)
// render: Function
// staticRenderFns: Array
```
--------------------------------
### Compile Vue Template to AST and Render Functions
Source: https://github.com/meituan-dianping/mpvue/blob/master/packages/vue-template-compiler/README.md
Compiles a Vue template string into an Abstract Syntax Tree (AST), a main render function, and static render functions. It can also report template syntax errors. Note that the generated render function uses 'with' and is not suitable for strict mode.
```javascript
const compiler = require('vue-template-compiler')
const result = compiler.compile(template, {
modules: [], // Optional: array of compiler modules
directives: { // Optional: object of custom directives
test (node, directiveMeta) {
// transform node based on directiveMeta
}
},
preserveWhitespace: true // Optional: preserve whitespace, defaults to true
})
// result object contains:
// ast: ASTElement | null
// render: string
// staticRenderFns: Array
// errors: Array
```
--------------------------------
### compiler.parseComponent
Source: https://github.com/meituan-dianping/mpvue/blob/master/packages/vue-template-compiler/README.md
Parses a Single-File Component (*.vue file) into a descriptor object.
```APIDOC
## POST compiler.parseComponent
### Description
Parses a .vue file content into a descriptor containing template, script, and style blocks.
### Method
POST
### Endpoint
compiler.parseComponent(file, [options])
### Parameters
#### Request Body
- **file** (string) - Required - The contents of the .vue file.
- **options** (object) - Optional - Configuration object, e.g., { pad: "line" }.
### Request Example
{
"file": "",
"options": { "pad": "line" }
}
### Response
#### Success Response (200)
- **template** (object) - Descriptor for the template block.
- **script** (object) - Descriptor for the script block.
- **styles** (array) - Descriptors for style blocks.
#### Response Example
{
"template": { "content": "", "start": 10, "end": 21 },
"script": { "content": "export default {}", "start": 32, "end": 50 }
}
```
--------------------------------
### Compile Vue Template to SSR Functions
Source: https://github.com/meituan-dianping/mpvue/blob/master/packages/vue-template-compiler/README.md
Compiles a Vue template string directly into instantiated SSR-specific render and static render functions. This method is optimized for server-side rendering performance and uses `new Function()`, making it not CSP-compliant.
```javascript
const compiler = require('vue-template-compiler')
const { render, staticRenderFns } = compiler.ssrCompileToFunction(template)
// render: Function (SSR optimized)
// staticRenderFns: Array (SSR optimized)
```
--------------------------------
### SVG Dot Model Creation and Update Logic
Source: https://github.com/meituan-dianping/mpvue/blob/master/benchmarks/svg/index.html
Defines a function to create an array of SVG dots, each with random initial positions and velocities. It also includes a 'step' function that iterates through all points and updates their positions based on their velocities, handling boundary collisions. This model is central to the animation.
```javascript
function createModel (count) {
var points = []
for (var i = 0; i < count; ++i) {
points.push({
x: Math.random() * WIDTH,
y: Math.random() * HEIGHT,
vx: Math.random() * 4 - 2,
vy: Math.random() * 4 - 2
})
}
return {
points: points,
step: step
}
function step () {
points.forEach(move)
}
function move (p) {
if (p.x > WIDTH || p.x < 0) p.vx *= -1
if (p.y > HEIGHT || p.y < 0) p.vy *= -1
p.y += p.vy
p.x += p.vx
}
}
```
--------------------------------
### Vue.js User Profile Data Binding
Source: https://github.com/meituan-dianping/mpvue/blob/master/examples/firebase/index.html
Displays user information using Vue.js template syntax. It binds name and email properties to the view and includes a placeholder for deletion or removal actions.
```html
{{user.name}} - {{user.email}}
```
--------------------------------
### Define mpvue Page Component
Source: https://context7.com/meituan-dianping/mpvue/llms.txt
Shows a standard Vue single-file component adapted for mpvue. It includes data binding, computed properties, methods, and integration with mini-program specific lifecycle hooks like onLoad and onPullDownRefresh.
```vue
{{ userInfo.nickName }}
{{ item.title }}{{ item.count }}
```
--------------------------------
### Reactive Data Operations with Vue.set and Vue.delete in mpvue
Source: https://context7.com/meituan-dianping/mpvue/llms.txt
This code illustrates how to leverage Vue.set and Vue.delete within mpvue components to manage reactive properties and array elements. It highlights the importance of these methods for triggering view updates when dynamically adding or removing data, contrasting them with direct assignment or index-based modification which are not reactive.
```javascript
export default {
data() {
return {
user: {
name: '张三',
age: 25
},
items: ['苹果', '香蕉', '橙子']
}
},
methods: {
addUserProperty() {
this.$set(this.user, 'email', 'test@example.com')
},
updateItem(index, newValue) {
this.$set(this.items, index, newValue)
},
removeUserProperty() {
this.$delete(this.user, 'email')
},
arrayOperations() {
this.items.push('葡萄')
this.items.pop()
this.items.shift()
this.items.unshift('西瓜')
this.items.splice(1, 1, '梨')
this.items.sort()
this.items.reverse()
},
replaceArray() {
this.items = this.items.filter(item => item !== '香蕉')
this.items = this.items.map(item => item.toUpperCase())
}
}
}
```
--------------------------------
### Compile Vue Template for SSR
Source: https://github.com/meituan-dianping/mpvue/blob/master/packages/vue-template-compiler/README.md
Compiles a Vue template string into SSR-specific render function code, optimizing for server-side rendering performance by converting parts of the template into string concatenation. This is used by default in vue-loader@>=12.
```javascript
const compiler = require('vue-template-compiler')
const result = compiler.ssrCompile(template, {
// Options similar to compiler.compile, but optimized for SSR
})
// result object contains SSR-optimized render functions and AST
```
--------------------------------
### Vue.js Form Validation Logic
Source: https://github.com/meituan-dianping/mpvue/blob/master/examples/firebase/index.html
Defines validation error messages for user input fields. This snippet demonstrates how to handle empty name fields and invalid email formats in a Vue component.
```javascript
const validationErrors = {
name: "Name cannot be empty.",
email: "Please provide a valid email address."
};
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.