Home > other >  Vue3 Composite API window.scrollTo element of ref Array
Vue3 Composite API window.scrollTo element of ref Array

Time:11-11

Anybody an idea how to get the offsetTop of an element in Vue3 with the composite API? Like this version of Vue2?

goto(refName) { 
  var element = this.$refs[refName];
  var top = element.offsetTop;     
  window.scrollTo(0, top);
}

i have in my setup():

const accordions = ref([]);
...
<Disclosure
    v-slot="{ open }"
    v-for="(region, index) of data"
    :key="index"
    :ref="(el) => pushToRef(el, index)"
  >...</Disclosure>

function pushToRef(el, index) {
  accordions[index] = el;
}

it is filled by elements of a v-for. I could get the proxy out of the array later. But not the offset:

const element = accordions[region]; 
console.log("Region: "   region); //got the name 
console.log("Element: ", element); // Proxy of element 
const top = element.offsetTop; // UNDEFINED ???
console.log("OffsetTop: "   top); // !!! Undefined 
window.scrollTo({ top: top, left: 0, behavior: "smooth", });

CodePudding user response:

I believe your code is running before the component is mounted. Try wrapping it in a onMounted

import { onMounted } from 'vue'

onMounted(() => {
  const element = accordions[region];
  const top = element.offsetTop;
  console.log("OffsetTop: "   top);
})

CodePudding user response:

I am not sure if you meant to mutate accordions as it's a ref object but if you are doing that in your actual code, you should avoid it and mutate the inner value instead i.e accordions.value.
Now, since Disclosure is a component and not an HTML element, vue's template ref won't refer to that element's DOM. It will refer to Vue Instance of the Disclosure component instead. You can read more on that here.
You need to access the HTML element's DOM like this: el.$el, then you can access all DOM properties including offsetTop.
In case you want to check all properties of a component instance, you can find them here.
Side note: This ref behavior is same in Options API as well i.e you will access DOM properties of a vue component in a similar way like this: this.$refs['REF_NAME'].$el

  • Related