current position:Home>Mpvue wechat applet

Mpvue wechat applet

2022-06-24 09:54:39Xuan Yu Shang

Catalog

One 、mpvue ( Vue in Mini Program )

Two 、 Initialize project

1. Check node and npm edition

2. install vue-cli The scaffold

3. establish mpvue project

4. Enter the project directory , Installation dependency

5. stay  project.config.json To configure  appid

6. perform , Generate dist Folder

7. Download wechat developer tools

8. Wechat developer tool opens the change project ( Whole project ) 

9. You can see the effect

3、 ... and 、mpvue Use of basic functions in

01. Global profile => app.json Applet configuration | Wechat open documents

02. Single page profile => main.json

03. Single page mount file => main.js

04. Page style

05. Binding method => and vue In the same

06. Life cycle

Four 、mpvue Use of advanced functions

01. Page Jump

1 - establish about Components , Configure mount components main.js

2 - stay app.json Configure this page in

3 - use wx.navigateTo Jump wx.navigateTo(Object object) | Wechat open documents

4 - Delete dist Folder , Re execution npm run dev 

5 - If there are parameters in the transfer process

02. Use vuex 

1. download vuex And create... In the root directory store Folder

2. stay store Create under folder index.js

3. stay store Create under folder state.js

4. stay store Create under folder actions.js

5. stay store Create under folder mutations.js 

6.  stay store Create under folder getters.js 

7. At the entrance file main.js Import

8. Use in components vuex 

03. Use local storage  

04. Share page  wx.showActionSheet(Object object) | Wechat open documents

3、 ... and 、 Start to develop wechat open documents for the project

Get user information

01 - Use wx.getUserProfile

02 - adopt wx.login obtain code wx.login(Object object) | Wechat open documents


One 、mpvue ( Vue in Mini Program )

  • mpvue.com
  • Launched by meituan engineers be based on Vue Encapsulated framework for developing small programs
  • A combination of native applets and Vue Characteristics
  • Component development

Two 、 Initialize project

1. Check node and npm edition

node -v && npm -v

2. install vue-cli The scaffold

npm install vue-cli -g

3. establish mpvue project

vue init mpvue/mpvue-quickstart  Project name 
//  Then you can return all the way , Follow up can be in project.config.json To configure 

4. Enter the project directory , Installation dependency

npm install

5. stay  project.config.json To configure  appid

appid : stay WeChat public platform After registering a , You can have

6. perform , Generate dist Folder

npm run dev

Because this is the development of small programs , Therefore, the browser will not be opened after execution , Because there's no need ~, Generated dist Folder That's what we need  

7. Download wechat developer tools

Stable version Stable Build Update log | Wechat open documents

8. Wechat developer tool opens the change project ( Whole project ) 

9. You can see the effect

3、 ... and 、mpvue Use of basic functions in

01. Global profile => app.json​​​​​​​ Applet configuration | Wechat open documents

02. Single page profile => main.json

notes  : The configuration of a single page overrides the global configuration

03. Single page mount file => main.js

notes : You need to use... In every page ,  Component instance .$mount() To mount the current component , Otherwise, the corresponding page cannot take effect

however , If it's just a component , Then don't write , Direct reference , then component Sign up to use

//  Import vue
import Vue from 'vue'
//  Import components 
import Index from './index.vue'
//  Generate a vue example 
const index = new Vue(Index)
//  Mount to element 
index.$mount()

04. Page style

<!-- //? The module specification  =>   Homepage module  -->
<template>
  <div class='index-layout'>
    <div>index123</div>
  </div>
</template>
<script>
export default {
  name: 'index'
}
</script>
<style>
/*  
     If you want to set the entire page style ( For example, height ), Need to be in page Set in 
     Each page has one page Wrapped in , amount to <page></page>
*/
page {
  height: 100%;
  text-align: center;
}
/*  Simply setting this will not take effect  */
.index-layout {
  height: 100%;
  background-color: #07c160;
}
</style>

05. Binding method => and vue In the same

06. Life cycle

except Vue Out of its own life cycle ,mpvue Also compatible with the applet life cycle , This part of life cycle hook comes from Wechat applet Page, except In exceptional circumstances , It is not recommended to use the lifecycle hook of an applet .​​​​​​​


Four 、mpvue Use of advanced functions

01. Page Jump

1 - establish about Components , Configure mount components main.js

2 - stay app.json Configure this page in

3 - use wx.navigateTo Jump wx.navigateTo(Object object) | Wechat open documents

​​​​​​​ stay mpvue Chinese vs vue-router Poor support , Many problems , Page Jump is provided by the applet API

  • wx.navigateTo()  Keep the current page , Back off
  • wx.redirectTo()  No reservation , Can't back
  • wx.switchTab()  Used in tabBar page

4 - Delete dist Folder , Re execution npm run dev 

notes : If it is a new page , Then you need to repackage , Otherwise, an error will be reported and will not take effect

5 - If there are parameters in the transfer process

Pass on

let data = {id : 1, name : ' Zhang San '}
// id  and  data  That is, the parameters passed  
wx.navigateTo({
     url: '/pages/about/main?id='+data.id+'&data=' + JSON.stringify(data)
})

receive  

mounted(){
   console.log(this.$mp.query.id,JSON.parse(this.$mp.query.data));
}

02. Use vuex 

1. download vuex And create... In the root directory store Folder

npm i vuex

2. stay store Create under folder index.js

import Vue from 'vue'
import Vuex from 'vuex'

import state from './state.js'
import mutations from './mutations.js'
import actions from './actions.js'
import getters from './getters.js'

Vue.use(Vuex)

const store = new Vuex.Store({
  state,
  mutations,
  actions,
  getters
})

export default store

3. stay store Create under folder state.js

export default {
  //  Initialization status 
  initName: 'star',
  initList: []
}

4. stay store Create under folder actions.js

export default {
  getList({
    commit
  }) {
    return new Promise((resolve, reject) => {
      // axios.get('/api/list').then(res => {
      //   commit('setList', res.data);
      //   resolve(res.data);
      // }).catch(err => {
      //   reject(err);
      // })
      let bool = true
      let data = [{
        name: ' Zhang San ',
        age: 18,
      }]
      if (bool) {
        commit('SET_LIST', data)
        resolve(data);
      }else{
        reject('error');
      }
    });
  }
}

5. stay store Create under folder mutations.js 

export default{
  //  Get list data 
  SET_LIST(state, value) {
    //  Assign a value to state Medium initList
    state.initList = value
  }
}

6.  stay store Create under folder getters.js 

export default {
  //  Get state Medium initName data 
  getInitName: state => state.initName,
}

7. At the entrance file main.js Import

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

import store from './store/index.js'
//  take store Mount to Vue For instance , So that all components can use store
Vue.prototype.$store = store

Vue.config.productionTip = false
App.mpType = 'app'

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

8. Use in components vuex 

<!-- //? The module specification  =>   Homepage module  -->
<template>
  <div class='index-layout' >
    <div @click="toAbout"> Jump to about page </div>
  </div>
</template>
<script>
import {mapState, mapGetters,mapMutations,mapActions } from 'vuex'
export default {
  name: 'index',
  computed:{
    //  Use mapGetters Of getInitName Method to get the initialized initName value 
    ...mapGetters(['getInitName']),
    //  Use mapState Get initName Value 
    ...mapState({
      initName: state => state.initName,
      initList: state => state.initList
    })
  },
  methods: {
    //  Get mutations As defined in GET_LIST Method 
    ...mapMutations(['SET_LIST']),
    //  Get actions As defined in getList Method 
    ...mapActions(['getList']),
  },
  mounted(){
    //  get data 
    console.log(this.initName); //star
    console.log(this.getInitName); //star

    //  Use actions As defined in getList Method request , get data 
    //  amount to  this.$store.dispatch('getList');
    this.getList()
    
    console.log(this.initList); //{ name: ' Zhang San ', age: 18}

    //  Use mutations As defined in SET_LIST Method to set the data 
    //  amount to    this.$store.commit('SET_LIST', { name: ' Li Si ', age: 20 })
    this.SET_LIST({
      name: ' Li Si ',
      age: 20
    })
    console.log(this.initList); //{ name: ' Li Si ', age: 20}
  }
}
</script>
<style>
page {
  height: 100%;
  text-align: center;
}
.index-layout {
  height: 100%;
  background-color: #07c160;
}
</style>

03. Use local storage  

//  What needs to be stored . Only native types are supported 、Date、 And be able to pass JSON.stringify Serialized objects .
wx.setStorageSync('key', 'value')
//  obtain 
wx.getStorageSync('key')

04. Share page  wx.showActionSheet(Object object) | Wechat open documents

share() {
  wx.showActionSheet({
    itemList: ['A', 'B', 'C'],
    success(res) {
      console.log(res.tapIndex)
    },
    fail(res) {
      console.log(res.errMsg)
    }
  })
}

3、 ... and 、 Start developing projects Wechat open documents

Get user information

wx.getUserProfile(Object object) | Wechat open documents

01 - Use wx.getUserProfile

<template>
  <div class='index-layout'>
    <div>index123</div>
    <button  @click="getUserProfile">  Get head nickname  </button>
  </div>
</template>
<script>
export default {
  name: 'index',
  mounted() {
    wx.login({
      success(res) {
        if (res.code) {
          // Initiate network request , hold code Pass it to the back end 
          // wx.request({
          //   url: 'https://example.com/onLogin',
          //   data: {
          //     code: res.code
          //   }
          // })
        } else {
          console.log(' Login failed !' + res.errMsg)
        }
      }
    })
  },
  methods: {
  getUserProfile(e) {
      //  Recommended  wx.getUserProfile  Get user information , Every time the developer obtains the user's personal information through the interface, the user needs to confirm 
      //  Developers keep the nicknames of avatars that users fill in quickly , Avoid repeated pop ups 
      wx.getUserProfile({
        desc: ' It is used to improve the membership information ', //  Declare the purpose of obtaining the user's personal information , The follow-up will be shown in the pop-up window , Please fill in carefully 
        //  Click allow 
        success: (res) => {
          console.log('success',res);
        },
        //  Click reject 
        fail: (err) => {
          console.log('fail',err);
        }
      })
    },
  }
}
</script>

notes : now Not recommended wx.getUserProfile or wx.getUserInfo 

02 - adopt wx.login obtain code wx.login(Object object) | Wechat open documents

mounted() {
    wx.login({
      success(res) {
        if (res.code) {
          // Initiate network request , hold code Pass it to the back end 
          wx.request({
            url: 'https://example.com/onLogin',
            data: {
              code: res.code
            }
          })
        } else {
          console.log(' Login failed !' + res.errMsg)
        }
      }
    })
  },

03 - Get the user's mobile number   Get cell phone number | Wechat open documents

<template>
    <button open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">
        Get cell phone number 
    </button>
</template>

<script>
export default {
  name: 'index',
  methods: {
    getPhoneNumber(e) {
      let code = e.target.code
      console.log(e.target.code);
      //  Put the cell phone number code Pass it to the back end 
      wx.request({
        url: 'https://example.com/onLogin',
        data: {
           code
        }
      })
    }
  }
};
</script>

 

 

 

copyright notice
author[Xuan Yu Shang],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/175/202206240907421618.html

Random recommended