What is the best way to incorporate a vanilla javascript function into a vue.js application?

Consider a vanilla JavaScript function like this:

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;

  });

}

This function changes the src of an image when a retina display is detected. How can one incorporate this function into an application built with vue.js? Where should the function be placed?

If the function is placed in mounted, it only works on the initial page load and not when navigating through SPA pages using the router:

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

The specific details of the retina function are not crucial, the main question is how to effectively utilize custom vanilla JavaScript functions within a vue.js application.

Answer №1

It is recommended to ensure that your code works within the mounted lifecycle hook. Are you making your modifications directly on this.$el.... or using a different approach?

Remember to check the documentation for any potential limitations, which can be found at https://v2.vuejs.org/v2/api/#mounted

Keep in mind that not all child components may have been mounted when the parent component's mounted hook is called. If you need to wait until the entire view has finished rendering, consider utilizing vm.$nextTick inside the mounted hook:

If you are working with child components, make sure to bundle them accordingly. Here is an example snippet of how you can handle this scenario:

mounted(){
  this.$nextTick(() => {
    // Your code logic here
  });
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is an alternative way to retrieve the page title when the document.title is unavailable?

Is there a way to retrieve the page title when document.title is not available? The code below seems to be the alternative: <title ng-bind="page.title()" class="ng-binding"></title> How can I use JavaScript to obtain the page title? ...

Angularjs directives failing to compute accurately~

I'm working with an AngularJS directive where the HTML template is compiled within the linker function. var htmlTemplate = '<img ng-src="~/img/logos/{{account.Logo}}" width="45" height="35" />' var linker = function (scope, element) ...

Converting Typescript objects containing arrays into a single array

Looking for some assistance with this problem :) I am trying to convert the object into an array with the following expected result: result = [ { id: 'test-1', message: 'test#1.1' }, { id: 'test-1', mess ...

Working with AngularJS $resource: including an array element in paramDefaults

I'm currently working with the twitch.tv API and utilizing the Angular $resource factory. My goal is to access the endpoint: GET /channels/:channel. What I want to achieve is to retrieve the channel for each element within an array. I attempted using ...

Material-UI - Switching thumb styles in a range slider

Looking for a way to style two entities differently on the Material-UI Slider? Entity A as a white circle and Entity B as a red circle? While using data-index can work, there's a flaw when sliding. Is there a better approach? if (data-index === 0) { ...

What is the best approach for retrieving and storing data in Vuex when working with multiple components containing input fields in Vue Router?

In the Vue CLI project I'm working on, there's a route called Settings which has 3 child components: SettingsA, SettingsB, and SettingsC. Each of these child components consists of approximately 15 input fields, making it impractical to include a ...

Unable to extract the 'id' property from 'params' object in Next.js 13.4 due to its undefined value

I am currently trying to retrieve the [id] URL parameter in Next.js 13.4, but I keep encountering an error stating that params is undefined. Despite extensive online research and seeking assistance from ChatGPT, all I could find were examples for older ve ...

What is an alternative method to retrieve POST fields in Express without relying on the bodyParser middleware?

Recent updates to Express have suggested to stop using the bodyParser middleware, as indicated by a debug message. Upon further research, it appears that bodyParser is simply a wrapper to the json and urlencoded middlewares. In its place, the latest versio ...

non-concurrent in Node.js and JavaScript

I'm a beginner in the world of NodeJS and I have a question that's been bugging me. Node is known for its asynchronous nature, but JavaScript itself also has asynchronous features (like setTimeout). So why weren't concepts like Promise intr ...

Angular 2: trigger a function upon the element becoming visible on the screen

How can I efficiently trigger a function in Angular 2 when an element becomes visible on the screen while maintaining good performance? Here's the scenario: I have a loop, and I want to execute a controller function when a specific element comes into ...

Using Selenium: Checking for existing dropdown values and incrementing if necessary

I am currently working on automating an application using Selenium Webdriver with Java. The web application I am testing has an Add button that, when clicked, triggers the activation of a dropdown menu. Subsequent clicks on the Add button reveal additional ...

Are undefined Static Properties an Issue in Mocked Classes? (Jest)

Currently, I am facing a challenge in mocking a class that includes a static property. jest.mock("../../src/logger/index"); import { Logger } from "../../src/logger/index"; // .. const LoggerMock = Logger as jest.MockedClass<typeof ...

Are you facing issues with Handlebars parsing?

I am struggling to identify the issue in my HTML/JS code. Here is my HTML/JS: <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> <script src="handlebars-v1.1.2.js"> ...

Creating a customized store locator using JSON data in WordPress for Google Maps API

I'm currently seeking a customized solution to implement a store locator using the Google Maps API within WordPress. Although there are numerous WordPress plugins available, I prefer a more tailored approach. Here are the specific requirements: ...

There are no Vue.js updates reflected in Heroku when using Laravel

I've encountered an issue with Heroku (PaaS). I'm in the process of launching my first project using Laravel, and I'm consistently making changes. It's my understanding that every modification made during development needs to be pushed ...

What is the best way to access props from a different file in a React application?

I am facing a challenge with my two files: EnhancedTableHead and OrderDialog. I need to access the props data from EnhancedTabledHead in my OrderDialog file. Is there a way to achieve this? Here is how my files are structured: //OrderDialog.jsx import ...

Manipulating selected values in VueJs v-select using methods

I am currently working on achieving the following goal: When I select the option "Alle openstaande" (result_id = 0), I want to select all these result_ids: [-1,-2,-3,-5,-7,-8,-11,-12] and deselect result_id 0. The variable mergedResults stores an array o ...

Refresh a div using jQuery and include PHP files for dynamic content updating

This is the code I am using to dynamically update divs containing PHP files: $(document).ready(function() { setInterval(function() { $('#ContentLeft').load('live_stats1.php').fadeIn("slow"); $('#ContentRight').load( ...

Enhance the way UV coordinates are generated for rotated triangles/faces within THREE.js

While researching how to map a square texture onto n-sided polyhedrons using a convex hull generator in THREE.js, I found that existing solutions did not fully address my issue. The challenge was to ensure that the texture was not distorted and appeared co ...

Tips for resolving TS7022 issue within Vue Composition API

I encountered an issue while attempting to import a component in my file that generated the following error message: TS7022: 'default' implicitly has type 'any' because it does not have a type annotation and is referenced directly or in ...