Use vue to complete the WeChat Public Number Web page short note

Posted by [e]r!k on Thu, 16 May 2019 11:11:37 +0200

Preface:

The company recently has a H5 page function, a simpler questionnaire function, nested in our WeChat public number.The chosen technology stack is Vue.WeChat's login and share interface is also used.ps: I'm Xiao Bai. If you have any questions, I want you to point out that writing articles is not only for recording, but also for discovering your own problems.Thank you!!!

Key features and issues encountered:

  1. Toggle Animation Left and Right
  2. Routing with parameter jumps
  3. Introduction of external font styles on the mobile side
  4. Use the htmtl2canvas screenshot function
  5. Use the WeChat interface (front part)
  6. Mobile Screen Adapter
  7. Mobile Click a page Click multiple times Execute a problem only once
  8. ios masks button problems by popping up the keyboard while using the input box
  9. Packaging project encountered static resource loading problem

1. Switch animation from left to right

--First I thought about using vue's mobile animation library for a long time, but the project was so small that I gave up the option to start writing by myself.First of all, I consider the transition effect.And found the relevant article reference.The code is as follows:

`<template>
  <div id="app">
    <transition :name="'fade-'+(direction==='forward'?'last':'next')">
      <router-view></router-view>
    </transition>
  </div>
</template>
<script>
export default {
  name: "app",
  data: () => {
    return {
      direction: ""
    };
  },
  watch: {
    $route(to, from) {
      let toName = to.name;
      const toIndex = to.meta.index;
      const fromIndex = from.meta.index;
      this.direction = toIndex < fromIndex ? "forward" : "";
    }
  }
}
</script>
<style scoped>
.fade-last-enter-active {
  animation: bounce-in 0.6s;
}
.fade-next-enter-active {
  animation: bounce-out 0.6s;
}
@keyframes bounce-in {
  0% {
    transform: translateX(-100%);
  }
  100% {
    transform: translateX(0rem);
  }
}
@keyframes bounce-out {
  0% {
    transform: translateX(100%);
  }
  100% {
    transform: translateX(0rem);
  }
}
</style>`

Reference resources: https://yq.aliyun.com/article...

2. Routing with parameter jumps

There are three ways to record this.
1. Take parameters directly in route-link:to:

<router-link :to="{name:'home', query: {id:1}}"> 

2. In this.$router.push with parameters:

Use query with parameters: parameters like get are spliced onto the url

this.$router.push({name:'home',query: {id:'1'}})
this.$router.push({path:'/home',query: {id:'1'}})

Use params with parameters: name only can be used similar to post without splicing

this.$router.push({name:'home',params: {id:'1'}}) 

Reference link: https://blog.csdn.net/jiandan...

3. Introducing external font styles on the mobile side

  1. The mobile side introduces external styles. I download the fonts from the font library directly, usually with a suffix of.ttf/.otf, etc.Create under asset file
    fonts file, put all font files in.
  2. Create a new.css file, which is equivalent to registering the fonts you download. You can customize the names of the fonts, but typically follow the previous names.src is the path to the file.

  3. Just use it where you need it: font-family:'PingFang'

4. Convert to pictures using htmtl2canvas screenshots

  1. Download the html2 canvas package first: cnpm I html2canvas-S / import html2canvas from'html2canvas';
  2. View Documents: Click in to generate pictures directly. Use the WeChat Long Press Save Pictures feature to save pictures
setTimeout(() => {  //The timer is used here because as soon as the page loads, I show pictures to prevent them from being generated at a point in time
      html2canvas(document.querySelector("#top"), {
        useCORS: true,  //Whether to attempt to load images from the server using CORS 
        logging: false,//Delete printed logs 
        allowTaint: false //This is similar to the first one but fails to use the toDataURL at the same time
      }).then(canvas => {
        let imageSrc = canvas.toDataURL("image/jpg"); // Path to divert img 
        this.imageSrc = imageSrc;  //Define a dynamic: the src is now assigned to the src image to display
        this.$refs.top.style.display = "none"; // Let other elements disappear on the page and show only pictures
      });
    }, 1000);

Off-topic topic: I was a bit confused when I did this.There are too few official documents. I encountered cross-domain problems with pictures at that time. I have been searching for them for a long time. Perhaps I have not carefully checked Jan's official parameters profile.Wasting a lot of time crying.

Reference link: http://html2canvas.hertzen.com/

5. Use the WeChat interface (front part)

We use the WeChat SDK interface mainly to do the login and sharing functions. First, look at the public platform of WeChat, and configure the back-end after doing a good job of privileges.The front end only needs to request data and can do some configuration.Here is the function of sharing to friends and circle of friends:

this.code = location.href; //Get the code first 
if (this.code.lastIndexOf("code=") != -1) {
  (this.code = this.code.substring(
    this.code.lastIndexOf("code=") + 5,
    this.code.lastIndexOf("&state")
  )),
    this.$axios
      .get("*******8?code=".concat(this.code))
      .then(function(t) {  //Get back-end parameters 
        localStorage.setItem("unionid", t.data.unionid);
        localStorage.setItem("openid", t.data.openid);
        localStorage.setItem("nickname", t.data.nickname);
        localStorage.setItem("headimgurl", t.data.headimgurl);
      });
}
this.url = encodeURIComponent(location.href.split("#/")[0];//Get the configured path
this.$axios.get(`*********?url=${this.url}`).then(res => {
  this.res = res.data;
  wx.config({
    debug: false, // Turn on debugging mode,
    appId: res.data.appId, // Required, unique identification of the enterprise number, fill in the enterprise number corpid here
    timestamp: res.data.timestamp, // Required, time stamp for signature generation
    nonceStr: res.data.nonceStr, // Required, generate a random string of signatures
    signature: res.data.signature, // Required, signed, see Appendix 1
    jsApiList: [
      "updateAppMessageShareData",
      "updateTimelineShareData",
      "showMenuItems",
      "hideAllNonBaseMenuItem"
    ] // Required, list of JS interfaces to use, all JS interfaces listed in Appendix 2
  });
  //Written with reference to the public platform:
  wx.ready(function() {
    wx.hideAllNonBaseMenuItem();
    wx.showMenuItems({
      menuList: [
        "menuItem:share:appMessage",
        "menuItem:share:timeline",
        "menuItem:favorite"
      ] // To display menu items, see Appendix 3 for all menu items
    });
    wx.updateTimelineShareData({
      title: "******", // Share Title
      desc: "*********", // Share Description
      link: "**********", // Share a link whose domain name or path must match the public number JS security domain name corresponding to the current page
      imgUrl: "******", // Share Icon
      success: function() {
        ***** Callback to execute after execution
      }
    });
    wx.updateAppMessageShareData({
      title: "*******", // Share Title
      desc: "*********", // Share Description
      link: "*********", // Share a link whose domain name or path must match the public number JS security domain name corresponding to the current page
      imgUrl: "********, // Share Icon
      success: function() {
        *******
      }
    });
  });
 }
 

6. Mobile Screen Adaptation

Now we move the screen adapter, I use rem, I also saw before that there is a library of felxable.js, and then went to check that there are better authors who gave up, and provided us a link, Hahahaha is really cute.Ready to take time to look carefully, the company's next project has come again, really overtime for a long time. In order to complete the project on schedule, immediately start a new project after completion, a little tired, this should be APP, no experience at all, can only be hard-skinned to do, or just meals, poor should not dare to make it again.
Share the code for rem adapter below:

//Default call once setting
 setHtmlFontSize();
 
 function setHtmlFontSize() {
     // 1. Get the width of the current screen
     var windowWidth = document.documentElement.offsetWidth;
     // console.log(windowWidth);
     // 2. Define Standard Screen Width Assumption 375
     var standardWidth = 375;
     // 3. Define the root element font size for a standard screen Assume 100px 1rem=100px 10px=0.1rem 1px 0.01rem
     var standardFontSize = 100;
     // 4. Calculate the font size of the root element corresponding to the current screen
     var nowFontSize = windowWidth / standardWidth * standardFontSize + 'px';
     // console.log(nowFontSize);
     // 5. Set the font size of the currently calculated root element to html
     document.querySelector('html').style.fontSize = nowFontSize;
 }
 // 6. Add an event that changes the screen width The js that triggers the calculation of the font size of the changing root element 
 window.addEventListener('resize', setHtmlFontSize);

Introduce this code into main.js and use the converter to convert px to rem.

7. Summary of other issues

  1. Click Event Click multiple times to execute only once:

     There are many other useful modifiers that can be used with the.once modifier, so you have time to check ~~
  2. When using the ios input box, the keyboard pops up to cover up events such as buttons below:

    We can register an unfocused event for input and set document.body.scroolTop = 0 when it loses focus.  
  3. Packaging projects encounter static resources not shown or path errors:

    I'm using vue-cil3. He put the configuration files in node_modules, which are described in the official documentation. If you need to modify the configuration,
    Create a new vue.config.js file, which will automatically overwrite the previous file.Mainly modified to: publicPath:'. /'.
    Documents already do not have a baseUrl, now all use publicPath, follow the document configuration ok ay. 
    
    

Ending:

That's about all the problems I've encountered, because the project is small, so I don't have too many problems.The process is really a bit distressed, my ability to solve problems independently is really very general, I do not know if there is no potential to be a programmer, so I am very anxious when problems occur, after a period of time, or there is no way to solve them, I will be more anxious.During my internship at my last company, my group leader pointed out that after coming to this question, I really thought about it for a long time.Now the company is still practicing, but the front end is just one person, Miss and Sister are good, but they do not need the vue framework, so the problem has to be solved separately.Front-end Miss is a tough person. When she encounters problems, she is really a clue to find out. Don't give up that. At first, we need to use flutter. My environment has been built for a long time. Finally, Miss did a good job with me.Really go there is the process of learning.I think perseverance is really a very precious quality in the world, and I want to have it!!!

  • Finally, I wish you all good health and happiness.Recently I played football with twisted feet. I cried and fainted for 1s. I was really inactive for a long time, and my opponent's friend was a man. When I played football, I felt weak.I??Is my little Ding a patient person?Every subsequent shot gives life to the shot.Badminton feet were sore all over the last hour and went to the hospital with a limp.happy ending!

Topics: Javascript Mobile Vue iOS axios