Category Archives: JavaScript

How to Use DOM to operate CSS

    1. Modify styles through JS: the styles modified by this method are inline styles with high priority. However, if “! Important” is used in the style, the modification of JS will not work.
	Syntax: element.style.styleName = styleValue ;      
	The style value must be a string
	Note: If the style of css contains " - " , this name is not legal in JS, you need to change this style name to camel naming, remove the " - " and change the
	initial letter to uppercase.

Read style:

	Syntax: element.style.styleName

The styles set and read through the style property are inline styles

    1. get the display style of the current element:
	Syntax: element.currentStyle.styleName 
	currentStyle is only supported by IE browser

In other browsers, you can use the getcomputedstyle() method to get the current style of the element. This method is a window method and can be used directly. This method will return a style object that encapsulates the corresponding style of the current element.

	Two parameters are required
	The first: the element to get the style
	The second: you can pass a pseudo-element, which is usually null

Note: the styles obtained through currentstyle and getcomputestyle are read-only and cannot be modified. If you want to modify them, you must use the style property </OL> to modify them

The addition, deletion and modification of DOM in JS Foundation

    1. document.createElement (); you need to pass in a tag name as a parameter. You will create a corresponding node according to the tag name and return the node. document.createTextNode (); you need to pass in a text content as the parameter appendChild ()
	Usage: parent element.appendChild( child node ).

A child of a node can be inserted before the new node

	Usage: Parent node. insertBefore( new node, old node );

Replacechild(); replace child node

	Usage: parent.replaceChild( new node, old node );

Removechild(); can delete a child node

	Usage: parent.removeChild(child node).

InnerHTML can also be used to add dom. Generally, the two methods are combined.

	e.g. city.innerHTML += " <li>GuangZhou</li> ";

Confirm (“); a prompt box with confirm and Cancel buttons will pop up. If the user clicks confirm, it will return true; otherwise, it will return false </ OL>

How to download files by post submission under Ajax

/*===================Download file
 * options:{
 * url:'',  //Download Url
 * data:{name:value}, //the datas you want to post
 * method:'post'
 * }
 */
var DownLoadFile = function (options) {
    var config = $.extend(true, { method: 'post' }, options);
    var $iframe = $('<iframe id="down-file-iframe" /&>');
    var $form = $('<form target="down-file-iframe" method="' + config.method + '" /&>');
    $form.attr('action', config.url);
    for (var key in config.data) {
        $form.append('<input type="hidden" name="' + key + '" value="' + config.data[key] + '" /&>');
    }
    $iframe.append($form);
    $(document.body).append($iframe);
    $form[0].submit();
    $iframe.remove();
}

Module build failed: Error: Couldn’t find preset “es2015” relative to directory

1. Error description

F:\WebstormProjects\euw\esa>npm install babel-plugin-component -D
npm WARN [email protected] requires a peer of ajv@^6.0.0 but none is installed. You must install peer dnpm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"dar
+ [email protected]
added 4 packages from 3 contributors in 13.118s
 
F:\WebstormProjects\euw\esa>npm run dev
 
> [email protected] dev F:\WebstormProjects\euw\esa
> webpack-dev-server --inline --progress --config build/webpack.dev.conf.js
 
 94% asset optimization
 
 ERROR  Failed to compile with 2 errors                                                                                                                                                                                          16:10:44
 
 error  in (webpack)-dev-server/client?http://localhost:8081
 
Module build failed: Error: Couldn't find preset "es2015" relative to directory "F:\\WebstormProjects\\euw\\esa"
    at F:\WebstormProjects\euw\esa\node_modules\babel-core\lib\transformation\file\options\option-manager.js:293:19
    at Array.map ()
    at OptionManager.resolvePresets (F:\WebstormProjects\euw\esa\node_modules\babel-core\lib\transformation\file\options\option-manager.js:275:20)
    at OptionManager.mergePresets (F:\WebstormProjects\euw\esa\node_modules\babel-core\lib\transformation\file\options\option-manager.js:264:10)
    at OptionManager.mergeOptions (F:\WebstormProjects\euw\esa\node_modules\babel-core\lib\transformation\file\options\option-manager.js:249:14)
    at OptionManager.init (F:\WebstormProjects\euw\esa\node_modules\babel-core\lib\transformation\file\options\option-manager.js:368:12)
    at File.initOptions (F:\WebstormProjects\euw\esa\node_modules\babel-core\lib\transformation\file\index.js:212:65)
    at new File (F:\WebstormProjects\euw\esa\node_modules\babel-core\lib\transformation\file\index.js:135:24)
    at Pipeline.transform (F:\WebstormProjects\euw\esa\node_modules\babel-core\lib\transformation\pipeline.js:46:16)
    at transpile (F:\WebstormProjects\euw\esa\node_modules\babel-loader\lib\index.js:50:20)
    at Object.module.exports (F:\WebstormProjects\euw\esa\node_modules\babel-loader\lib\index.js:173:20)
 
 @ multi (webpack)-dev-server/client?http://localhost:8081 webpack/hot/dev-server ./src/main.js
 
 error  in ./src/main.js
 
Module build failed: Error: Couldn't find preset "es2015" relative to directory "F:\\WebstormProjects\\euw\\esa"
    at F:\WebstormProjects\euw\esa\node_modules\babel-core\lib\transformation\file\options\option-manager.js:293:19
    at Array.map ()
    at OptionManager.resolvePresets (F:\WebstormProjects\euw\esa\node_modules\babel-core\lib\transformation\file\options\option-manager.js:275:20)
    at OptionManager.mergePresets (F:\WebstormProjects\euw\esa\node_modules\babel-core\lib\transformation\file\options\option-manager.js:264:10)
    at OptionManager.mergeOptions (F:\WebstormProjects\euw\esa\node_modules\babel-core\lib\transformation\file\options\option-manager.js:249:14)
    at OptionManager.init (F:\WebstormProjects\euw\esa\node_modules\babel-core\lib\transformation\file\options\option-manager.js:368:12)
    at File.initOptions (F:\WebstormProjects\euw\esa\node_modules\babel-core\lib\transformation\file\index.js:212:65)
    at new File (F:\WebstormProjects\euw\esa\node_modules\babel-core\lib\transformation\file\index.js:135:24)
    at Pipeline.transform (F:\WebstormProjects\euw\esa\node_modules\babel-core\lib\transformation\pipeline.js:46:16)
    at transpile (F:\WebstormProjects\euw\esa\node_modules\babel-loader\lib\index.js:50:20)
    at Object.module.exports (F:\WebstormProjects\euw\esa\node_modules\babel-loader\lib\index.js:173:20)
 
 @ multi (webpack)-dev-server/client?http://localhost:8081 webpack/hot/dev-server ./src/main.js

2. The reason for the error

The contents of the .babelrc file

{
  "presets": [
    ["env", {
      "modules": false,
      "targets": {
        "browsers": ["> 1%", "last 2 versions", "not ie <= 8"]
      }
    }],
    "stage-2"
  ],
  "plugins": ["transform-vue-jsx", "transform-runtime"]
}

To

{
  "presets": [["es2015", { "modules": false }]],
  "plugins": [
    [
      "component",
      {
        "libraryName": "element-ui",
        "styleLibraryName": "theme-chalk"
      }
    ]
  ]
}

3. Solution

Execute the following command:

npm install --save-dev babel-preset-es2015
F:\WebstormProjects\euw\esa>npm install --save-dev babel-preset-es2015
npm WARN deprecated [email protected]: ????  Thanks for using Babel: we recommend using babel-preset-env now: please read babeljs.io/env to update!
npm WARN [email protected] requires a peer of ajv@^6.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
 
+ [email protected]
added 1 package from 1 contributor in 9.707s
 
F:\WebstormProjects\euw\esa>

Solution to build error in Vue project (error in static/JS)/vendor.xxxxx.js from UglifyJs)

The project that has been running very well suddenly reported an error in build. The error message is as follows:

ERROR in static/js/vendor.f1c68aa2d5e85847d30e.js from UglifyJs
Unexpected token name «i», expected punc «;» [./node_modules/element-ui/src/utils/merge.js:2,0][static/js/vendor.f1c68aa2d5e85847d30e.js:17064,11]
Build failed with errors.

In uglifyjs’ GitHub issues # 78, we found such a solution: because uglifyjs only supports Es5, and element UI may introduce a part of the writing of ES6, so webpack packaging fails. The final solution given in issue is to replace uglify JS with uglify es of beta version (beta version introduces support for es2015 +). You need to execute the command NPMI - D in the front-end working directory uglifyjs-webpack-plugin@beta

However, after trying, we found that the problem of build error is still unsolved. After searching for the problem, we decided to use bable to parse the element UI. To complete this operation, we only need to modify the build error in the front-end folder/ webpack.base.conf The. JS file can be modified as follows:
before modification

module: {
rules: [
...
{
test: /\.js$/,
loader: 'babel-loader',
include: [resolve('src'), resolve('test')]
},

After modification

 

module: {
rules: [
...
{
test: /\.js$/,
loader: 'babel-loader',//Note that elementUI's source code needs to be parsed using ES6
include: [resolve('src'), resolve('test'),resolve('/node_modules/element-ui/src'),resolve('/node_modules/element-ui/packages')]
},
...

It is equivalent to adding element UI to the package that needs to be parsed by Babel.

After that, execute NPM run build again, and the build is successful.

Vant Applet: The Usage of Vant-dialog in Before-close


## Wrong
//index.wxml
<van-dialog 
	use-slot 
	title="title" 
	show="{{ showDialog }}"
	beforeClose="beforeClose">
  <view class="dialog-content"></view>
</van-dialog>
//index.js
page({
	data:{
		showDialog:true
	},
	beforeClose() {
	    return new Promise((resolve) => {
	      setTimeout(() => {
	        if (action === 'confirm') {
	          resolve(true);
	        } else {
	          resolve(false);
	        }
	      }, 1000);
	    });
	})
  },
  ## Right
  //index.wxml
	<van-dialog 
	use-slot 
	title="title" 
	show="{{ showDialog }}"
	before-close="{{ beforeClose }}">
	  <view class="dialog-content">
	  </view>
	</van-dialog>
	//index.js
	Page({
	  data: {
	  	showDialog:true,
	    beforeClose(action) {
         return new Promise((resolve) => {
            setTimeout(() => {
              if (action === 'confirm') {
                resolve(true);
              } else {
                resolve(false);
              }
            }, 1000);
          });
        },
	  }
	})
	If you want to get a property in data beforeClose, you can't use this.data to get the data in data, so you can't get the data
	You can get the data through the WeChat applet - getCurrentPages (get the current page stack)
	const pages = getCurrentPages()
    let page = pages[pages.length-1]
    page is the current page
    At this point you can use page.data to get the properties of the current page

When starting Vue project: cannot find module ‘webpack cli/bin/config yargs’ error resolution

An error is reported when starting Vue project: cannot find module ‘webpack cli/bin/config yargs’, as shown in the following figure:

the reason for this error is that the version of webpack and webpack dev server is incompatible. The solution is as follows:

input below the VUE project:
npm uninstall  webpack -g
npm uninstall -g webpack-dev-server
uninstall and install:
npm install [email protected] --save-dev
npm install [email protected] --save-dev

Restart the project, success!

Vue elementui: solution for error: avoided redundant navigation to current location: “/xxx”

The error report shows that the route is repeated, which has no effect on the function, but obsessive-compulsive disorder looks uncomfortable.

Specific performance: repeatedly click the tab menu in the element UI, this error will be reported.

Solution:

 Solve the problem that vue-router in the navigation bar of ElementUI reports an error when repeatedly clicking the menu in version 3.0 or above
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}

Router file index.js Add the above code in.
Note: router or vuerouter depends on the definition in your file.

Vue: How to Solve error avoided redundant navigation to current location: “/xxx”

The solution of error: avoided redundant navigation to current location: “/ xxx” in the project

error reporting shows that the route is repeated, which has no impact on the function.

resolvent:

Router file index.js Add the following code to the

// Solve the problem that vue-router in the navigation bar of ElementUI reports an error when repeatedly clicking the menu in version 3.0 or above
const originalPush = Router.prototype.push
Router.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}

Solve the problem of repeatedly clicking the same route console in Vue to report an error

After Vue router is upgraded to 3.1. X, when repeatedly clicking the navigation, the console will report an error. Although it does not affect the use of the function, it can not be ignored.

Error information

Cause of error

After Vue router ≥ v3.1, the callback form is changed to promise API, and promise is returned. If no error is caught, the console will always display the warning as shown in the figure above.

How to Solve This Error

[method 1] reduce the version

npm i [email protected] -S

[method 2] add the following code in the router folder

const routerPush = Router.prototype.push
Router.prototype.push = function push(location) {
  return routerPush.call(this, location).catch(error=> error)
}

[method 3] capture exception

// router.push error
this.$router.push(route).catch(err => {
    console.log('outpur error',err)
})

[method 4] complete the third parameter of router

// Completing the third argument of router.push()
this.$router.push(route, () => {}, (e) => {
    console.log('output error',e) 
})