This is the fourth day of my participation in the August Text Challenge.More challenges in August
These are the problems I have recorded in the past one or two years after I encountered problems in the development. After I become more experienced, there will be fewer problems and no records, so I only recorded these problems for the time being. I will update the posts when I encounter problems later, hoping that it will be helpful to you who are just in touch with front-end development
Vue2 pack after display blank resolved
Solutions:
Change the export path of the bulid module in index.js under config
module.exports = { build: { index: path.resolve(__dirname, '.. /dist/index.html'), assetsRoot: path.resolve(__dirname, '.. /dist'), assetsSubDirectory: 'static', assetsPublicPath: './', productionSourceMap: true, devtool: '#source-map', productionGzip: false, productionGzipExtensions: ['js', 'css'], bundleAnalyzerReport: process.env.npm_config_report } }Copy the code
AssetsPublicPath defaults to ‘/’, which is the root directory. Our index. HTML and static are in the same directory. So change it to ‘./ ‘;
Run NPM run build again
Vue + Element package is messy
Solutions:
The reason is that the order of import in main.js overwrites the styles you write
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import App from './App'
import Vue from 'vue'
import router from './router'
Copy the code
Adjust the order
The Element icon is not displayed in VUe2
Solutions:
Modify biuld the utils. Js, CTRL + f search ExtractTextPlugin. Extract, modify the code block
return ExtractTextPlugin.extract({ use: loaders, fallback: 'vue-style-loader', publicPath: '.. /.. / '})Copy the code
The PAGE does not change when the URL parameter changes or the browser is refreshed
Solutions:
Adding listening Events
Watch: {'$route' (to, from) {if(to.params){this.xxx(); Console. log(to,this.$route.query)}}}Copy the code
Listen to retrieve the data or use the forceUpdate method
this.$forceUpdate();
Copy the code
Invalid to change URL forward or backward
Solutions:
1. Set the history mode in the route
2. Use the onHashchange event in hash mode
Mounted () {// Check whether the browser does not refresh the page after routing changes. () => { let currentPath = window.location.hash.slice(1) if (this.$route.path ! == currentPath) { this.$router.push(currentPath) } }, false) }Copy the code
To solve the cross domain
Config dev module in index.js
const test = "http://xxx.xx.xx.xx:xxxx"; //apiurl
module.exports = {
dev: {
// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {
'/api': {
target: test,
changeOrigin: true,
pathRewrite: {
'^/api': '/api'
}
}
}
Copy the code
Do not add this code to access to localhost: 8080 / API/login, after joining will be redirected to the XXX. Xx, xx, xx, XXXX/API/login, if…
Route hops are not at the top
Methods a
ScrollBehavior (to,from,saveTop){if(saveTop){return saveTop; }else{ return {x:0,y:0} } }Copy the code
Update: Vue-router no longer supports this method, replace the following:
Document.documentelement is used when a page specifies a DTD, that is, when a DOCTYPE is specified.
Document.body is used when the page does not have a DTD, that is, when no DOCTYPE is specified.
router.afterEach((to, from) => { let bodySrcollTop = document.body.scrollTop if (bodySrcollTop ! == 0) { document.body.scrollTop = 0 return } let docSrcollTop = document.documentElement.scrollTop if (docSrcollTop ! == 0) { document.documentElement.scrollTop = 0 } })Copy the code
Method 2
main.js
router.beforeEach((to, from, next) => { // chrome document.body.scrollTop = 0 // firefox document.documentElement.scrollTop = 0 // safari Window.pageyoffset = 0 next()}) // chromedocument.body.scrollTop = 0 // firefoxdocument.documentElement.scrollTop = 0 // safariwindow.pageYOffset = 0Copy the code
Use different styles for mobile and browser
var sUserAgent = navigator.userAgent.toLowerCase(); var bIsIpad = sUserAgent.match(/ipad/i) == "ipad"; var bIsIphoneOs = sUserAgent.match(/iphone os/i) == "iphone os"; var bIsIphone = sUserAgent.match(/iphone/i) == "iphone"; var bIsMidp = sUserAgent.match(/midp/i) == "midp"; Var bIsUc7 = sUserAgent. Match (/ rv: 2. / I) = = "rv: 2." var bIsUc = sUserAgent.match(/ucweb/i) == "ucweb"; var bIsAndroid = sUserAgent.match(/android/i) == "android"; var bIsCE = sUserAgent.match(/windows ce/i) == "windows ce"; var bIsWM = sUserAgent.match(/windows mobile/i) == "windows mobile"; if ( bIsIpad || bIsIphoneOs || bIsIphone || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM ) { console.log('h5'); require("./assets/style/h5.less"); this.$store.dispatch("ish5"); } else { console.log('web'); require("./assets/style/web.less"); this.$store.dispatch("isweb"); }Copy the code
Smooth position to anchor point
First add d_jump’s class as an anchor point
<div class="holidayList scroll_content">
<ul>
<li v-for="(v,i) in imgList" :key="i.id" :id="'loc'+i" class="d_jump">
<img class="imgLogo" :src="v.logo" alt>
</li>
</ul>
</div>
Copy the code
Then define the method to manipulate the anchor point jump(index)
<ul>
<li @click="jump(0)">xxx1</li>
<li @click="jump(1)">xxx2</li>
<li @click="jump(2)">xxx3</li>
<li @click="jump(3)">xxx4</li>
</ul>
Copy the code
method:
Jump (index) {/ / class = "d_jump" add anchor point let jump = document. QuerySelectorAll (". D_jump "); let total = jump[index].offsetTop; let distance = document.documentElement.scrollTop || document.body.scrollTop; Let step = total / 50; let step = total / 50; if (total > distance) { smoothDown(); } else { let newTotal = distance - total; step = newTotal / 50; smoothUp(); } function smoothDown() { if (distance < total) { distance += step; document.body.scrollTop = distance; document.documentElement.scrollTop = distance; setTimeout(smoothDown, 10); } else { document.body.scrollTop = total; document.documentElement.scrollTop = total; } } function smoothUp() { if (distance > total) { distance -= step; document.body.scrollTop = distance; document.documentElement.scrollTop = distance; setTimeout(smoothUp, 10); } else { document.body.scrollTop = total; document.documentElement.scrollTop = total; }}}Copy the code
The refresh browser loses store information in vuex
To refresh all listening pages in app.vue, add the following code directly
// Store created() {if (sessionStorage.getitem ("store")) {// Read the status information in sessionStorage before page loading this.$store.replaceState(Object.assign({}, this.$store.state, JSON.parse(sessionStorage.getItem("store")))) } window.addEventListener("beforeunload", Sessionstorage.setitem ("store", json.stringify (this.$store.state))})}Copy the code
An error occurs when you click route repeatedly
Add the following code to /router/index
import Vue from 'vue'
import Router from 'vue-router'
const routerPush = Router.prototype.push
Router.prototype.push = function push(location) {
return routerPush.call(this, location).catch(error => error)
}
Copy the code
Returns the pre-encryption parameter
function objKeySort(arys, isEncodeURI) { isEncodeURI = isEncodeURI == undefined ? true : isEncodeURI; let newkey = Object.keys(arys).sort(); let parStr = ""; for (var i = 0; i < newkey.length; i++) { if (isEncodeURI) { parStr += newkey[i] + "=" + encodeURIComponent(arys[newkey[i]]) + "&"; } else { parStr += newkey[i] + "=" + arys[newkey[i]] + "&"; } } return parStr == "" ? "" : parStr = parStr.substr(0, parStr.length - 1); // Return the sorted new arguments}Copy the code
Get the background binary stream picture
The background interface returns the binary stream image format, it’s a picture on the network, but it’s going to print something that looks like gibberish, it’s actually a binary stream format, and then you need to convert it to base64, vue+ AXIos
$axios.get('/ API /chkcode.aspx', {responseType: 'arrayBuffer'}). Then (response => {// return 'data:image/ PNG; base64,' + btoa( new Uint8Array(response.data).reduce((data, key) => data + String.fromCharCode(key), "))}). Then (res => {console.log(res) => {console.log(res) => {console.log(res); (error) => { console.log(error) }) }Copy the code
Vue-photo-preview full screen is invalid
Asynchronously fetching data requires a line of code to refresh and reset
this.$previewRefresh();
Copy the code
Common error resolution
When the following situations occur
compilation. templatesPlugin is not a function
TypeError: Cannot destructure property createHash
of ‘undefined’ or ‘null’
- Install the latest webpack4 or above
npm add webpack@latest
Copy the code
- Delete node_modules and reinstall it. You are advised to use the following command
npm install rimraf -g
rimraf node_modules
npm i
Copy the code
vue-loader was used without the corresponding plugin. Make sure to include
Reinstall the vue_loader
npm i --save-dev vue-loader
Copy the code
Module build failed: Error: Cannot find module ‘file-loader’
Reinstall the vue_loader
npm i --save-dev file-loader
Copy the code