How to import functions from different js file in a Vue+webpack+vue-loader project

前端 未结 4 1124
轮回少年
轮回少年 2021-02-01 01:39

(See end for why this is not a dupe of How do I include a JavaScript file in another JavaScript file?)

Javascipt + Vue + webpack + vue-loader noob... stumbling on the si

4条回答
  •  囚心锁ツ
    2021-02-01 02:06

    I was trying to organize my vue app code, and came across this question , since I have a lot of logic in my component and can not use other sub-coponents , it makes sense to use many functions in a separate js file and call them in the vue file, so here is my attempt

    1)The Component (.vue file)

    //MyComponent.vue file
    
    
    
    
    

    2)The External js file

    //Mylib.js
    let exports = {};
    
    // this (vue instance) is passed as that , so we
    // can read and write data from and to it as we please :)
    exports.myfuncA = (that) => {
      that.message =
      "you hit ''myfuncA'' function that is located in Mylib.js  and data.name = " +
        that.name;
    };
    
    exports.myfuncB = (that) => {
      that.message =
      "you hit ''myfuncB'' function that is located in Mylib.js and now I will change the name to Nassim";
      that.name = "Nassim"; // <-- change name to Nassim
    };
    
    exports.myfuncC = (that) => {
      that.message =
      "you hit ''myfuncC'' function that is located in Mylib.js and now I will change the name back to Bob";
      that.name = "Bob"; // <-- change name to Bob
    };
    
    export default exports;
    

    3)see it in action : https://codesandbox.io/s/distracted-pare-vuw7i?file=/src/components/MyComponent.vue


    edit

    after getting more experience with Vue , I found out that you could use mixins too to split your code into different files and make it easier to code and maintain see https://vuejs.org/v2/guide/mixins.html

提交回复
热议问题