Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use custom JavaScript code in a Vue.js app

I'm trying to insert JavaScript code in a Vue.js router app. I need to load data from the CMS the app is served from. In order to get the data from the CMS I have to use a JavaScript library from the CMS which is not made for Vue and is not exporting it's class/functions like modern JS. So I import the JS library from in the index.html by a script tag. This works as intended.

But now I have to use the class from this CMS JavaScript library. Before writing this as a Vue-Router app I just have used Vue for templating purposes. So I had some code packed in the window.onload event handler. I have to create an instance for the CMS data access class. But this leads to a build error (using vue-cli build). Since there are no understandable error messages from the build process I have to use trial and error. Even simple variable assignments like var a = 1 seem not to be allowed. A console.log('something') works. But nothing else seemes to be allowed (except defining the onload-event handler)

I have added this code in a <script> Tag inside App.vue (which was created by vue-cli create)

window.onload = function() {
    
    try {
        // Instantiate class obj for CMS data access
        cmsDataAccessObj = new CMSAccessData();
        waitForPlayerData = true;
    }
    catch (e) {
        console.error(e);
    }
}

UPDATE

After testing the different solutions from the answers I got aware that using non-instance variables seems to cause the build errors.

This gives an error:

        waitForPlayerData = true;

This works:

        this.waitForPlayerData = true;
like image 820
user2123796 Avatar asked Oct 15 '22 01:10

user2123796


2 Answers

I wouldn't recommend using window.load to run your code. There are more native approaches to do this in Vue.js.

What you should do in the case you want to run it in the main component of the app before it's been loaded is to put the code inside the beforeCreate lifecycle hook of the main component.

...
beforeCreate () {
  this.cmsDataLoader()
},
methods: {
  cmsDataLoader () {
    try {
        // Instantiate class obj for CMS data access
        cmsDataAccessObj = new CMSAccessData();
        waitForPlayerData = true;
    }
    catch (e) {
        console.error(e);
    }
  }
}
...

This will run the code everytime a component is created before the creation. You could also use the created lifecycle hook if you want to run it after the creation of the component.

Check the following link for more information about lifecycle hooks.

like image 59
sebasaenz Avatar answered Oct 21 '22 05:10

sebasaenz


The best way to place JavaScript in Vue.js App is mounted function, it is called when the component is loaded:

export default {
    name: "component_name",
    mounted() {
        let array = document.querySelectorAll('.list_item');
    },
}
like image 37
Michael Adams Avatar answered Oct 21 '22 05:10

Michael Adams