P粉2826276132023-08-29 11:43:49
First, read Vue’s documentation about template references. There is a toggle button in the upper left corner of the page to switch between options API and combined API syntax.
Using variable references depends on the Vue version and/or syntax you are using.
<div ref="someRefName"></div>
Vue 2 / Options API
The variable should be a string matching the ref on the element
const refVar = "someRefName" this.$refs[refVar].scrollIntoView({ behavior: "smooth" });
Vue 3 / Combination API
Variables should be assigned the value ref()
(requires import). The name of the constant should match the ref name on the element
const someElement = ref() // 赋值给模板中的某个元素 someElement.value.scrollIntoView({ behavior: "smooth" });
Options API and composition API should not be mixed, so only one syntax is used.
In both cases you can have multiple elements with the same ref name, at which point Vue will create an array containing all the refs with the same name, so to access a specific element you will also need to use an index.
The following are some simplified examples. Hopefully they solve your remaining problems and you can modify them as needed.
Options API codesandbox example
Combined API codesandbox example