How to use vue to complete the WeChat public account webpage
Apr 29, 2019 am 09:57 AM
There is an H5 page function, a relatively simple questionnaire function, nested in our WeChat official account. The technology stack chosen is Vue. WeChat’s login and sharing interfaces are also used.
Main functions and problems encountered:
- Left and right switching animation
- Routing with parameter jump
- Move Introduce external font styles on the end
- Use html2canvas screenshot function
- Use WeChat interface (front-end part)
- Mobile terminal screen adaptation
- Mobile terminal clicks a page The problem of only executing once after clicking multiple times
- When using the input box in ios, the keyboard pops up and covers the button problem
- The packaged project encounters the problem of loading static resources
1 .Switch animations left and right
--First of all, I considered using vue’s mobile animation library. I looked at it for a long time, but the project was very small, so I gave up and started writing by hand. The first thing I considered was the transition effect. And found relevant article references. The code is as follows:
`<template> <p id="app"> <transition :name="'fade-'+(direction==='forward'?'last':'next')"> <router-view></router-view> </transition> </p> </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: https://yq.aliyun.com/article...
2. Routing with parameter jump
This is just for recording, There are three methods.
1. Directly bring parameters in route-link:to:
<router-link :to="{name:'home', query: {id:1}}">
2. Bring parameters in this.$router.push:
Use query with parameters: similar to get The parameters passed will be spliced ??into the url
this.$router.push({name:'home',query: {id:'1'}}) this.$router.push({path:'/home',query: {id:'1'}})
Use params with parameters: Only name can be used, similar to post, the parameters will not be spliced
this.$router.push({name:'home',params: {id:'1'}})
Reference link: https://blog.csdn.net /jiandan...
3. The mobile terminal introduces external font styles
- The mobile terminal introduces external styles. What I use is to directly download the fonts from the font library. The general suffix is .ttf/.otf etc. Create a
fonts file under the asset file and put all the font files into it. - Create a new .css file, which is equivalent to registering the fonts you downloaded. You can customize the names for the fonts, but generally they still follow the previous names. src is the path where the file is located.
- Just use it where needed: font-family: "PingFang"
4. Use the htmtl2canvas screenshot function, Convert to image
- First download the html2canvas package: cnpm i html2canvas -S / import html2canvas from 'html2canvas';
- View the document: Click in to directly generate the image. Long press on WeChat to save the image. Function to save
setTimeout(() => { //這里用定時器是因為頁面一加載出來我就展示的是圖片 為了防止圖片還未生成 給點時間 html2canvas(document.querySelector("#top"), { useCORS: true, //是否嘗試使用CORS從服務(wù)器加載圖像 logging: false,//刪除打印的日志 allowTaint: false //這個和第一個很像 但是不能同時使用 同時使用toDataURL會失效 }).then(canvas => { let imageSrc = canvas.toDataURL("image/jpg"); // 轉(zhuǎn)行img的路徑 this.imageSrc = imageSrc; //定義一個動態(tài)的 :src 現(xiàn)在是賦值給src 圖片就會展現(xiàn) this.$refs.top.style.display = "none"; // 讓頁面上其他元素消失 只顯示圖片 }); }, 1000);
Off topic: I was really confused when I was doing this. There are too few documents on the official website. At that time, I encountered a cross-domain problem with images, and I searched for it for a long time. Maybe I didn’t read the parameter configuration file of the official website carefully. A lot of time was wasted, crying.
Reference link: http://html2canvas.hertzen.com/
5. Using the WeChat interface (front-end part)
We use the WeChat SDK interface mainly for login And the sharing function, first go to the WeChat public platform to check it out, and then configure the backend after correcting the permissions. The front end only needs to request data and perform some configuration. Here we mainly introduce the functions of sharing to friends and sharing to Moments:
this.code = location.href; //首先獲取code 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) { //獲取后端傳會來的參數(shù) 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]);//獲取配置的路徑 this.$axios.get(`*********?url=${this.url}`).then(res => { this.res = res.data; wx.config({ debug: false, // 開啟調(diào)試模式, appId: res.data.appId, // 必填,企業(yè)號的唯一標識,此處填寫企業(yè)號corpid timestamp: res.data.timestamp, // 必填,生成簽名的時間戳 nonceStr: res.data.nonceStr, // 必填,生成簽名的隨機串 signature: res.data.signature, // 必填,簽名,見附錄1 jsApiList: [ "updateAppMessageShareData", "updateTimelineShareData", "showMenuItems", "hideAllNonBaseMenuItem" ] // 必填,需要使用的JS接口列表,所有JS接口列表見附錄2 }); //參考公眾平臺寫的: wx.ready(function() { wx.hideAllNonBaseMenuItem(); wx.showMenuItems({ menuList: [ "menuItem:share:appMessage", "menuItem:share:timeline", "menuItem:favorite" ] // 要顯示的菜單項,所有menu項見附錄3 }); wx.updateTimelineShareData({ title: "******", // 分享標題 desc: "*********", // 分享描述 link: "**********", // 分享鏈接,該鏈接域名或路徑必須與當(dāng)前頁面對應(yīng)的公眾號JS安全域名一致 imgUrl: "******", // 分享圖標 success: function() { ***** 執(zhí)行結(jié)束后執(zhí)行的回調(diào) } }); wx.updateAppMessageShareData({ title: "*******", // 分享標題 desc: "*********", // 分享描述 link: "*********", // 分享鏈接,該鏈接域名或路徑必須與當(dāng)前頁面對應(yīng)的公眾號JS安全域名一致 imgUrl: "********, // 分享圖標 success: function() { ******* } }); }); }
6. Mobile screen adaptation
Now we are adapting to the mobile screen. I use rem, which I have seen before. It was said that there is a felxable.js library. Later I checked it and found that a better author had given up and provided us with a link. Hahahaha, it’s so cute. I'm going to take the time to take a closer look. The next project of the company is here again. I have really worked overtime for a long time. In order to complete the project as scheduled, I started a new project immediately after completion. I am a little tired. This one should be an APP. I have no experience at all. , Ao Ao can only bite the bullet and do it, it still has to be cooked properly, and the poor fresh-graduated dog does not dare to make mistakes.
Share the rem adaptation code below:
//默認調(diào)用一次設(shè)置 setHtmlFontSize(); function setHtmlFontSize() { // 1. 獲取當(dāng)前屏幕的寬度 var windowWidth = document.documentElement.offsetWidth; // console.log(windowWidth); // 2. 定義標準屏幕寬度 假設(shè)375 var standardWidth = 375; // 3. 定義標準屏幕的根元素字體大小 假設(shè)100px 1rem=100px 10px = 0.1rem 1px 0.01rem var standardFontSize = 100; // 4. 計算當(dāng)前屏幕對應(yīng)的根元素字體大小 var nowFontSize = windowWidth / standardWidth * standardFontSize + 'px'; // console.log(nowFontSize); // 5. 把當(dāng)前計算的根元素的字體大小設(shè)置到html上 document.querySelector('html').style.fontSize = nowFontSize; } // 6. 添加一個屏幕寬度變化的事件 屏幕變化就觸發(fā)變化根元素字體大小計算的js window.addEventListener('resize', setHtmlFontSize);
Introduce this code into main.js, and then use the converter to convert px to rem.
7. Summary of other issues
1. Click event is executed only once when clicked multiple times:
You can use the .once modifier and there are many useful modifiers. Everyone has You can take a look at the time~~
2. When using the ios input box, the keyboard bounces up and blocks the buttons and other elements below:
We can register a loss of focus event for the input , when the focus is lost, set document.body.scoolTop = 0;
3. The packaged project encounters the phenomenon that static resources are not displayed or the path is wrong:
I use vue-cil3, which puts the configuration files in node_modules. The official document describes it. If you need to modify the configuration,
just create a new vue.config.js file, and it will automatically overwrite the previous one. document. The main modification is to: publicPath: "./",
The document no longer has a baseUrl, and now all uses publicPath. Just follow the document configuration and it will be ok.
Related tutorials: Vue framework video tutorial
##
The above is the detailed content of How to use vue to complete the WeChat public account webpage. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Backdrop-filter is used to apply visual effects to the content behind the elements. 1. Use backdrop-filter:blur(10px) and other syntax to achieve the frosted glass effect; 2. Supports multiple filter functions such as blur, brightness, contrast, etc. and can be superimposed; 3. It is often used in glass card design, and it is necessary to ensure that the elements overlap with the background; 4. Modern browsers have good support, and @supports can be used to provide downgrade solutions; 5. Avoid excessive blur values and frequent redrawing to optimize performance. This attribute only takes effect when there is content behind the elements.

Define@keyframesbouncewith0%,100%attranslateY(0)and50%attranslateY(-20px)tocreateabasicbounce.2.Applytheanimationtoanelementusinganimation:bounce0.6sease-in-outinfiniteforsmooth,continuousmotion.3.Forrealism,use@keyframesrealistic-bouncewithscale(1.1

Usetheelementwithinatagtocreateasemanticsearchfield.2.Includeaforaccessibility,settheform'sactionandmethod="get"attributestosenddatatoasearchendpointwithashareableURL.3.Addname="q"todefinethequeryparameter,useplaceholdertoguideuse

rel="stylesheet"linksCSSfilesforstylingthepage;2.rel="preload"hintstopreloadcriticalresourcesforperformance;3.rel="icon"setsthewebsite’sfavicon;4.rel="alternate"providesalternateversionslikeRSSorprint;5.rel=&qu

HTML5parsershandlemalformedHTMLbyfollowingadeterministicalgorithmtoensureconsistentandrobustrendering.1.Formismatchedorunclosedtags,theparserautomaticallyclosestagsandadjustsnestingbasedoncontext,suchasclosingabeforeaandreopeningitafterward.2.Withimp

ThetargetattributeinanHTMLanchortagspecifieswheretoopenthelinkeddocument.1._selfopensthelinkinthesametab(default).2._blankopensthelinkinanewtaborwindow.3._parentopensthelinkintheparentframe.4._topopensthelinkinthefullwindowbody,removingframes.Forexte

Use elements and set the action and method attributes to specify the data submission address and method; 2. Add input fields with name attribute to ensure that the data can be recognized by the server; 3. Use or create a submission button, and after clicking, the browser will send the form data to the specified URL, which will be processed by the backend to complete the data submission.

Vue provides v-if, v-else-if, v-else and v-show to handle conditional rendering; 1. Use v-if, v-else-if and v-else to control element rendering based on the true and false values of the expression. v-if is the initial condition, v-else-if is used for multi-condition judgment, v-else is placed last without expression, these instructions must be used continuously on the same level elements; 2. v-show switches element visibility through the display attribute of CSS, and elements always exist in the DOM, suitable for frequent switching scenarios; 3. The core difference between v-if and v-show is that v-if lazy rendering, switching overhead is high but is conducive to initial performance, v-show always renders and cuts
