Despite being logged in the Mounted() function, the Vue JS value fails to update

Trying to display a value inside my custom range slider on Vue. I have successfully implemented the slider in vanilla JS within the 'mounted()' lifecycle hook, and although I can log the value from this hook, it does not render or update the data value.

New to Vue and thinking that maybe this needs to be done in the computed object, but unsure of how to go about it,

<template>
  <div class="slidecontainer">
    <input type="range" min="1" max="100" value="50" class="slider" id="slider" />
    <div id="selector">
        <div class="selector-thumb">
           <p>{{rangeValue}}</p>
        </div>
    </div>
    <div class="d-flex">
      <div>
        <p>R5 000</p>
        <p>min</p>
      </div>
      <div style="margin-left:auto">
        <p >R200 000</p>
        <p >max</p>
      </div>
    </div>
  </div>
</template>

<script>

export default {
    data:function(){
        return{
            rangeValue:0
        }
    },
    mounted(){
        var slider = document.getElementById("slider");
        var selector = document.getElementById("selector");

        slider.oninput = function(){
            selector.style.left = this.value + "%";
            this.rangeValue = this.value;
            console.log(this.rangeValue)
        }
    }
};
</script>

Answer №1

Give this a try without relying on document.getElementById() or similar methods. When working within a framework, you can accomplish what you need without it.

<template>
  <div class="slidecontainer">
    <input v-model="rangeValue" type="range" min="1" max="100" value="50" class="slider"  />
    <div :style="{left: rangeValue + '%'}" id="selector">
        <div class="selector-thumb">
           <p>{{rangeValue}}</p>
        </div>
    </div>
    <div class="d-flex">
      <div>
        <p>R5 000</p>
        <p>min</p>
      </div>
      <div style="margin-left:auto">
        <p >R200 000</p>
        <p >max</p>
      </div>
    </div>
  </div>
</template>

<script>

export default {
    data:function(){
        return{
            rangeValue:50
        }
    },
};
</script>

If you absolutely must access an element directly, use ref like so:

<div ref="myBox"></div>

You can then access your element with: this.$refs.myBox

Note that if you try to access the element within mounted or created, you may encounter undefined since the element is not yet rendered. To ensure everything is ready for access, use $nextTick().

this.$nextTick(()=> {
   let element = this.$refs.myBox;
})

Additionally, Promise support is available:

await this.$nextTick();
let element = this.$refs.myBox;

Remember, the created or mounted method should be asynchronous in this case.

Answer №2

Make sure to utilize an arrow function in your function() as it does not properly track this.

slider.oninput = () => {
  selector.style.left = this.value + "%";
  this.rangeValue = this.value;
  console.log(this.rangeValue)
}

By using an arrow function, you can maintain the reference to this and access your data effectively.

Update: Upon closer inspection, I realize that this.value is being used without being defined in vue-data. Only this.rangeValue should be accessible at this stage.

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

"Exploring the utilization of Access Control Lists within the Algolia Search platform

Looking for the best method to handle access control lists in Algolia. We have lists of items, but prefer not to use a universal list. Each user has unique listings. Our application utilizes an ACL logic - is it possible to integrate this access logic wi ...

Storing the current date and time in a MySQL database using NodeJs

I'm having an issue inserting a DATETIME field into my MySQL database. var dt = require('moment')().format('YYYY-MM-DD HH:mm:ss'); pool.query( `insert into login(id, id_utente, data_login) values(NULL,?,?)`, [result ...

Navigation guard error: Caught in an infinite redirect loop

I have set up a new vue3 router and configured different routes: const routes = [ { path: "/", name: "home", component: HomeView, }, { path: "/about", name: "about", component: () => ...

What is the best way to integrate a Svelte component into a vanilla JS project without including Svelte as a dependency in the main project?

Is there a way to import a Svelte component into a project that does not have Svelte as a dependency? Imagine creating an npm package with a Svelte component and installing it in different projects without needing to add Svelte as a dependency. The package ...

What are the best practices for managing large amounts of data using jQuery and PHP with AJAX?

When I attempt to pass a large JavaScript array to PHP using the $.ajax method of jQuery, with Content-Type set as JSON and data sent as RAW, I encounter an issue. In PHP, I retrieve the data using file_get_contents('php://input'). Despite every ...

Null document element in AJAX

I am encountering an error message indicating: Uncaught TypeError: Cannot read property 'documentElement' of null When using the following code: function respondHandler() { if(xmlHttp.readyState == 4){ if(xmlHttp.status == 200){ xmlRespo ...

AngularJS: Organizing Controllers Horizontally Within ngRepeat

My data consists of a table with 100 rows, each representing a complex object that is an instance of a specific type. User interactions trigger operations on these objects individually, with each row having unique operations independent of the others. $sc ...

Design personalized social media icons that allow users to easily share the link of the current page

Currently, I am working on creating a widget that includes social sharing buttons. The goal is for these buttons to share the URL of the current page when clicked on various social media platforms. For instance, I attempted to integrate a Twitter share but ...

Headers cannot be set again after they have been sent to the client in Express Node

I attempted to create a post request for login with the following code: router.post('/login', async(req, res) =>{ const user = await User.findOne({gmail: req.body.gmail}) !user && res.status(404).json("user not matched") c ...

Using more than one variable for filtering in Vue.js

I've been busy working on implementing table filtering in Vue.js. So far, I have successfully filtered the table by name and date. However, I'm now facing a challenge with adding another filter along with them. If you want to check out my curren ...

Facing a problem with querying interfaces and types in TypeScript

My goal is to pass a variable to an RTK Query API service that uses a typescript interface: const device_id: unique symbol = Symbol(props.id); const { data: device, isFetching, isLoading, } = useGetAssetsByIdQuery(device_id, { pollingInterv ...

The Else clause is executing twice in the jQuery code

https://jsfiddle.net/mpcbLgtt/2/ Creating a function that adds card names to an array named deck and their IDs to another array called cardIds when a div with the class "card" is clicked. The cards available are: <div class='card' id=' ...

Organize my JavaScript code by implementing a function

I have repetitive javascript code that I would like to refactor into a function. Is there a way to streamline this process and make the code more efficient? The two functions I want to consolidate are: bright() $(VARIABLE).find('.info').fadeTo ...

Encountering an _FSEventStreamCreate error while setting up Vue3 installation

After using Vue2 for my studies, I decided to make the switch to Vue3. I started by uninstalling Vue2 on my Mac: npm uninstall vue-cli -g Next, I installed Vue3: npm install -g @vue/cli Upon checking the Vue version, I found it to be: (base) Tims-iMac-Pr ...

Issue: unable to establish a connection to [localhost:27017]

Upon executing node app.js, an error message is displayed: Failed to load c++ bson extension, using pure JS version Express server listening on port 3000 events.js:85 throw er; // Unhandled 'error' event ^ Error: failed to conn ...

An in-depth guide on implementing the Module Pattern in Typescript for an established JavaScript Module Pattern

I am relatively new to both Javascript and Typescript. I have been tasked with converting Javascript code to Typescript. I have come across a Module pattern that seems to return itself instead of exposing private methods and properties (please correct me ...

Submitting an mvc partial view form to send data from the parent view

I am currently working on a MVC 5 App where I have a Parent View that includes a Partial View, allowing users to load images. Upon submitting, the Parent view calls a .Ajax function defined within it, which in turn calls a Method/Controller. My requireme ...

Enhance your Three.js experience: Effortlessly Panning Panoramas with Smooth E

I am currently working on a 6 cube panorama project and using this demo as a reference: The dragging functionality in this demo is controlled by mouse events. I am looking to implement easing so that the panorama cube follows the mouse smoothly. I underst ...

Using jQuery to store the name of a Div in a variable and subsequently invoking it in a function

Recently, I've been grappling with a task involving storing a div name in a variable for easier editing and incorporating it into standard actions like show/hide. My code functions perfectly without the variables, but introducing them causes the div ...

Displaying JSON array data across three different pages using AngularJS and Ionic framework

I have an array of categories with multiple products. I want to display these categories on a category page. When a category is clicked, it should redirect to the product page and show the relevant products. Similarly, when a product is clicked, it shou ...