简体   繁体   中英

How to add vanilla javascript function vue.js app?

for example I have vanilla JS function:

 if (window.devicePixelRatio >= 2) { document.querySelectorAll('img.retina').forEach(function (e) { let parts = e.src.split('.'); let ext = parts.pop(); if (parts.join('.').indexOf('@2x') == -1) e.src = parts.join('.') + '@2x.' + ext; }); }

Which just change the src of image if js detect retina display. How can I use it in application using vue.js (where to put this function)?

If I put it into mounted, it doesnt work If I navigate throught SPA pages with router, it works only on first page load:

 new Vue({ el: "#app", router, render: h => h(App), mounted() { retinaFunction(); }, })

the retina function is not important, I am mostly asking where and how can I use custom function in vanilla js in vue.js application.

I would expect it to work in mounted , are you doing your modifications on this.$el.... or something else?

Note the caveat in the docs, https://v2.vuejs.org/v2/api/#mounted

Note that mounted does not guarantee that all child components have also been mounted. If you want to wait until the entire view has been rendered, you can use vm.$nextTick inside of mounted:

Do you have child components? Perhaps you need to bundle it:

mounted(){
  this.$nextTick(() => {
    this.$el....;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM