uniapp introduces modular js files and non-modular js files

Method 1: Import common js files, such as user.js

1.1, attributes and methods are written inside a variable

const user={
    login:true,
    isLogin:function(data){
        console.log("展示用户登录信息")
    }
}
export default user;

 1.2, can also be written separately

function isLogin(data){
    console.log("展示用户登录信息")
}
function getMobile(data){
    console.log("22222222")
}

export default {
    isLogin,
    getMobile
}

  Quoted in the .vue page:

<script>
    // 绝对路径,@指向项目根目录,在cli项目中@指向src目录
    import userfrom '@/common/user.js';
    // 相对路径
    import user from '../../common/user.js';

    export default {
        ...
        methods: {
            test(){
                user.isLogin()  //具体使用
            }
        }
    }

</script>

Notice

  • js files do not support /importing at the beginning

Method 2: Put user.js in the entry file main.js and make it a global method

import user from './common/user.js';
Vue.prototype.$user = user;

Quoted in the .vue page:

<script>
    export default {
        ...
        methods: {
            test(){
                this.$user.isLogin()//具体使用
            }
        }
    }
</script>

Method 3: Import a third-party modular .js file, such as md5.js encrypted file, which can be placed in the common folder and referenced as a normal .js file. The modularized one is exposed as an object through module.exports :

var exports = createMethod();
if (COMMON_JS) {
    module.exports = exports;
} else {
    root.md5 = exports;
    if (AMD) {
        define(function () {
            return exports;
        });
    }
}

Quoted in the .vue page: 

<script>
    import md5 from '../../common/md5.js';
    export default {
        ...
        methods: {
            test(){
                let sign = md5(getSignStr(arrKeys, arrValues)).toUpperCase();
            }
        }
    }
</script>

Method 4: H5 developed by uniapp, importing third-party non-modular.js files, such as nomodule.js, is a pure js file, without module.exports exposed as an object, which is placed in the common folder, as above If you import it like that, you will be prompted that it cannot be found. At this time, you should put the nomodule.js in the static folder. When uniapp releases H5, the content under the static file will not be compiled, and import the global js in the entry.html file, and in the .vue Just quote directly from the page

4.1、nomodule.js

function isNoModule(data){
    console.log("3333333")
}

4.2, and introduce global js in the entry.html file

<script charset="utf-8" src="<%= BASE_URL %>static/nomodule.js"></script>

4.3. Reference in the .vue page

<script>
    export default {
        ...
        methods: {
            test(){
                isNoModule();
            }
        }
    }
</script>

Guess you like

Origin blog.csdn.net/LzzMandy/article/details/126669128