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.
The operating environment of this tutorial: windows7 system, vue2.9.6 version, DELL G3 computer.
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) + '.' + oldNum.charAt(len - 3) + 'k' 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 '@/common/utils/util.js' 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 '@/common/utils/util.js''
method call of the file that needs to call this method
util.transNum(num)
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!