How to use better scroll the element when the parameter is a letter
How to use better scroll the element when the parameter is a letter
In my webApp project, I want to click a letter, and the relative content will be scrolled to display.
Here is js code:
<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 used vue 2.9.3
But I got a error:
[Vue warn]: Error in callback for watcher "letter": "TypeError: Cannot read property '0' of undefined"
who can help me?
<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 should add :ref="key"
<div
class="area"
v-for="(item, key) of cities"
:key="key"
:ref="key"
>
1 Answer
1
I think there is a time when watch function run, this.$refs[this.letter]
is not available yet. So you might want to check:
this.$refs[this.letter]
watch:
letter ()
if (this.letter && this.$refs[this.letter])
const element = this.$refs[this.letter][0]
this.scroll.scrollToElement(element)
Your cities
has different ref, you don't need to access [0] element
cities
watch:
letter ()
if (this.letter && this.$refs[this.letter])
const element = this.$refs[this.letter]
this.scroll.scrollToElement(element)
What's the error? Can you include template code of your Vue's component?
– ittus
Sep 7 '18 at 1:58
I have fixed, see my update, thank you
– stack
Sep 7 '18 at 2:00
I've updated my answer. Please check
– ittus
Sep 7 '18 at 4:08
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
I have tested as you said, but it failed again
– stack
Sep 7 '18 at 1:50