Tips for optimizing scrolling of a specific element with a letter parameter

For my web application project, I am trying to implement a feature where clicking on a letter will scroll to display the relevant content. Below is the JavaScript code snippet:

<script>
 import Bscroll from 'better-scroll'
 export default {
   name: 'CityList',
   props: {
     cities: Object,
     hotCities: Array,
     letter: String
   },
   watch: {
     letter () {
       if (this.letter) {
         const element = this.$refs[this.letter][0]
         this.scroll.scrollToElement(element)
       }
     }
   },
   mounted () {
     this.scroll = new Bscroll(this.$refs.wrapper)
   }
 }
</script>

I am using Vue 2.9.3, but encountered an error:

[Vue warn]: Error in callback for watcher "letter": "TypeError: Cannot read property '0' of undefined"

Can anyone assist me with solving this issue?

<div
  class="area"
  v-for="(item, key) of cities"
 :key="key"
>
  <div class="title border-topbottom">{{key}}</div>
  <div class="item-list">
    <div
      class="item border-bottom"
      v-for="innerItem of item"
      :key="innerItem.id"
    >
      {{innerItem.name}}
    </div>
  </div>
</div>

I realized that I should add `:ref="key"` as shown below:

<div
  class="area"
  v-for="(item, key) of cities"
 :key="key"
 :ref="key"
>

Answer №1

There may come a point during the execution of the watch function where this.$refs[this.letter] is not yet accessible. In order to handle this situation, it's recommended to verify the availability:

watch: {
  letter () {
    if (this.letter && this.$refs[this.letter]) {
      const element = this.$refs[this.letter][0]
      this.scroll.scrollToElement(element)
    }
  }
}

If your cities has a different reference, there is no need to access the [0] element.

   watch: {
      letter () {
        if (this.letter && this.$refs[this.letter]) {
          const element = this.$refs[this.letter]
          this.scroll.scrollToElement(element)
        }
      }
    }

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

Create a new function within the GraphQL Resolvers file

I am trying to define a function within the same ts file as where I specify the resolvers export const resolvers = { Query: { books: () => { return [ { title: 'Harry Potter and the Chambe ...

Vue.js crashes happen when trying to integrate ag-Grid in Jest testing

Within my Vue.js project, I have implemented testing for the login page using Jest: import Vuex from "vuex"; import { shallowMount, createLocalVue } from "@vue/test-utils"; import LoginForm from "@/components/LoginForm.vue"; import store from "@/store"; ...

Retrieve HTML content from an AJAX request and stylize it

In the Laravel project scenario, customers have the ability to choose a date using a datepicker. Once a date is selected, the available times are displayed to the customer. To achieve this functionality, I utilized Ajax to send the selected date to the dat ...

Three.js functions smoothly on both Android devices and desktop computers using Chrome, unfortunately it is not compatible with Safari

After diving into learning three.js, I decided to incorporate it into my angular 11 project. I created a simple demo using a SphereBufferGeometry and deployed it on github pages. Surprisingly, when I accessed it on an android phone, everything worked perfe ...

Utilizing jQuery's each() function to create a seamless loop of background images in a

Struggling with looping the background image in a slick slider? Check out the code snippet below. var json = [ { "img_url": "https://via.placeholder.com/500x500?text=1" }, { "img_url": "https://via.placeholder.com/500x500?text=2" }, { "img_url": "ht ...

What is the best way to make a Dojo TitlePane overlap using CSS?

My dilemma involves a jsfiddle featuring two TitlePane widgets in the central pane's top right corner. Currently, clicking on the right TitlePane ("Switch Basemap") moves the left TitlePane ("Map Overlays") to the left. What I want is for the right Ti ...

How to set default props in Vue Select component?

I have been utilizing the vue-multiselect plugin from this website: Given that I plan to use it frequently, I am interested in establishing some default props. For instance, my aim is to have the selectLabel prop set as an empty string and possibly con ...

Struggling to access properties of a javascript object while trying to slice it within table pagination

As I work on this program, my goal is to apply a function to an Array of objects to display rows with information from this group of users. However, TypeScript is throwing various errors when I try to access this information. I'm unsure of what I&apos ...

What is the best way to set a default function in a mongoose schema?

After spending quite a few hours trying to resolve this issue, I have finally turned to Stack Overflow for help. The problem I'm facing is with the promise pending errors on a specific field where I need to set a default value. Here's the code s ...

What is the method for defining a monkey patched class in a TypeScript declarations file?

Let's say there is a class called X: class X { constructor(); performAction(): void; } Now, we have another class named Y where we want to include an object of class X as a property: class Y { xProperty: X; } How do we go about defining ...

Rearrange DIV elements by clicking a button that redirects you to a different webpage

Consider a scenario with two distinct pages: website.com/page1 website.com/page2 Page 1 contains multiple buttons, each leading to Page 2. On Page 2, there are various content sections (divs). Is there a straightforward meth ...

What is the main file that vue-cli-service utilizes for entry?

Interested in a project utilizing vue, webpack, babel, npm? You can launch it with npm run server. While exploring how this command functions, I came across vue-cli-service serve in the package.json file. But how exactly does vue-cli-service initialize ...

HTML and CSS3 - styling a curved path

Can someone assist me in creating a curved line with fading edges using css3/html5, similar to the design shown in this image https://i.sstatic.net/8GFk6.png I came across this example on CodePen, but the edges are not fading as I would like them to. .bo ...

Passing various length values in AngularJS using stateParams

I am facing an issue with passing values of different lengths to the same state: For instance <li href="#/app/list/value1"> <li href="#/app/list/value1/value2"> Within my state definition, I have the following .state('app.list', ...

Creating a dynamic method to set data for a stacked bar chart in chart.js

In the following code snippet, you can see how my stacked bar chart is rendered using Angular: <canvas baseChart [datasets]="barChartData" [labels]="barChartLabels" [options]="barChartOptions" [legend]="barChartLegend" [chartType]=" ...

Toggle the visibility of a table row depending on the selected value of a Radio button

I have a jQuery script that I am working on, which toggles the visibility of table rows based on the selection of radio buttons. The current code functions properly when a radio button is clicked, but I would like to enhance it to automatically show or hid ...

How to retrieve the time duration in minutes between a start and end time in JavaScript to

I have conducted a thorough search on Stack Overflow and other platforms but could not find an answer to my specific question. While I did come across posts related to this topic, they did not address the issue I am facing. Problem: My challenge involves ...

What is the best way to send extra parameters to an ajax callback function?

Currently, I am implementing an ajax call in the following manner: util.AjaxCall(url, successCallbackFunction, errorCallbackFunction); function successCallbackFunction(result) { // Result returned from Ajax } Although everything is functioning correc ...

Javascript Using Promise to Await Ajax Content Loading

As a newcomer to JavaScript, I am exploring ways to traverse a DOM that utilizes Checkboxes for filtering results and displays them through Ajax. The checkboxes are organized in 4 levels: Grand Parent Parent Child Grand Child My goal is ...

What is the method to retrieve a javascript object from within a string template?

I am trying to find a way to map data from an object into a string template using JavaScript. Here is an example of the string and object I am working with: const menu = { breakfast: { description:'something' } meal: { d ...