Home > Web Front-end > Front-end Q&A > How to create and call global methods in vuejs

How to create and call global methods in vuejs

青灯夜游
Release: 2023-01-11 09:22:33
Original
4544 people have browsed it

Create and call a global method: 1. Customize a method under any file in the src directory of the vue project; 2. Use the import statement in the "main.js" file to introduce the custom method and add the The method is mounted on the vue instance; 3. On the required page, use the "$vue instance.method name()" statement to call the method.

How to create and call global methods in vuejs

The operating environment of this tutorial: windows7 system, vue2.9.6 version, DELL G3 computer.

Vue.js creates and calls global methods

In the vue project, first customize a method under any file in src, for example as follows

  transNum (num) {
    if (typeof (num) === 'undefined') {
      return 0
    } else {
      let oldNum = num.toString().trim()
      let len = oldNum.length
      if (len <= 3) {
        return num
      } else {
        let newNum = oldNum.substr(0, len - 3) + &#39;.&#39; + oldNum.charAt(len - 3) + &#39;k&#39;
        return newNum
      }
    }
  }
Copy after login

Method 1: Mount to the Vue instance

Example: introduce this method in the main.js file of the vue project and mount the method to the vue instance. Add the following code to the main.js file

import myutil from &#39;@/common/utils/util.js&#39;

Vue.prototype.$myutil = myutil
Copy after login

. When using it, you can directly pass it through

$myutil.transNum(num)
Copy after login

. Method 2: Import through import

In the

import util from &#39;@/common/utils/util.js&#39;&#39;
Copy after login

method call of the file that needs to call this method

util.transNum(num)
Copy after login

Description:

If you want to write the method call in {{}}, the method can only be introduced through the first method. The specific reason is related to the life cycle of vue, so I won’t go into details.

Related recommendations: "vue.js Tutorial"

The above is the detailed content of How to create and call global methods in vuejs. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template