Home  >  Article  >  Web Front-end  >  How to create and call global methods in vuejs

How to create and call global methods in vuejs

青灯夜游
青灯夜游Original
2021-09-26 18:30:044444browse

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
      }
    }
  }

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

. When using it, you can directly pass it through

$myutil.transNum(num)

. Method 2: Import through import

In the

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

method call of the file that needs to call this method

util.transNum(num)

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!

Statement:
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