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"
>