Vue js refs html

Template Refs ​

While Vue’s declarative rendering model abstracts away most of the direct DOM operations for you, there may still be cases where we need direct access to the underlying DOM elements. To achieve this, we can use the special ref attribute:

ref is a special attribute, similar to the key attribute discussed in the v-for chapter. It allows us to obtain a direct reference to a specific DOM element or child component instance after it’s mounted. This may be useful when you want to, for example, programmatically focus an input on component mount, or initialize a 3rd party library on an element.

Accessing the Refs ​

To obtain the reference with Composition API, we need to declare a ref with the same name:

script setup> import  ref, onMounted > from 'vue' // declare a ref to hold the element reference // the name must match template ref value const input = ref(null) onMounted(() =>  input.value.focus() >) script> template> input ref="input" /> template>

If not using , make sure to also return the ref from setup() :

export default  setup()  const input = ref(null) // .  return  input > > >

The resulting ref is exposed on this.$refs :

script> export default  mounted()  this.$refs.input.focus() > > script> template> input ref="input" /> template>

Note that you can only access the ref after the component is mounted. If you try to access $refs.input input in a template expression, it will be null on the first render. This is because the element doesn’t exist until after the first render!

If you are trying to watch the changes of a template ref, make sure to account for the case where the ref has null value:

watchEffect(() =>  if (input.value)  input.value.focus() > else  // not mounted yet, or the element was unmounted (e.g. by v-if) > >)

Refs inside v-for ​

When ref is used inside v-for , the corresponding ref should contain an Array value, which will be populated with the elements after mount:

script setup> import  ref, onMounted > from 'vue' const list = ref([ /* . */ ]) const itemRefs = ref([]) onMounted(() => console.log(itemRefs.value)) script> template> ul> li v-for="item in list" ref="itemRefs">  > li> ul> template>

When ref is used inside v-for , the resulting ref value will be an array containing the corresponding elements:

script> export default  data()  return   list: [ /* . */  ] > >, mounted()  console.log(this.$refs.items) > > script> template> ul> li v-for="item in list" ref="items">  > li> ul> template>

It should be noted that the ref array does not guarantee the same order as the source array.

Function Refs ​

Instead of a string key, the ref attribute can also be bound to a function, which will be called on each component update and gives you full flexibility on where to store the element reference. The function receives the element reference as the first argument:

input :ref="(el) =>  /* assign el to a property or ref */ >">

Note we are using a dynamic :ref binding so we can pass it a function instead of a ref name string. When the element is unmounted, the argument will be null . You can, of course, use a method instead of an inline function.

Ref on Component ​

This section assumes knowledge of Components. Feel free to skip it and come back later.

ref can also be used on a child component. In this case the reference will be that of a component instance:

script setup> import  ref, onMounted > from 'vue' import Child from './Child.vue' const child = ref(null) onMounted(() =>  // child.value will hold an instance of  >) script> template> Child ref="child" /> template>
script> import Child from './Child.vue' export default  components:   Child >, mounted()  // this.$refs.child will hold an instance of  > > script> template> Child ref="child" /> template>

If the child component is using Options API or not using , the The referenced instance will be identical to the child component’s this , which means the parent component will have full access to every property and method of the child component. This makes it easy to create tightly coupled implementation details between the parent and the child, so component refs should be only used when absolutely needed — in most cases, you should try to implement parent / child interactions using the standard props and emit interfaces first.

An exception here is that components using are private by default: a parent component referencing a child component using won’t be able to access anything unless the child component chooses to expose a public interface using the defineExpose macro:

script setup> import  ref > from 'vue' const a = 1 const b = ref(2) // Compiler macros, such as defineExpose, don't need to be imported defineExpose(  a,  b >) script>

When a parent gets an instance of this component via template refs, the retrieved instance will be of the shape < a: number, b: number >(refs are automatically unwrapped just like on normal instances).

The expose option can be used to limit the access to a child instance:

export default  expose: ['publicData', 'publicMethod'], data()  return   publicData: 'foo',  privateData: 'bar' > >, methods:  publicMethod()  /* . */ >, privateMethod()  /* . */ > > >

In the above example, a parent referencing this component via template ref will only be able to access publicData and publicMethod .

Источник

Component Instance ​

This page documents the built-in properties and methods exposed on the component public instance, i.e. this .

All properties listed on this page are readonly (except nested properties in $data ).

$data ​

The object returned from the data option, made reactive by the component. The component instance proxies access to the properties on its data object.

interface ComponentPublicInstance  $data: object >

$props ​

An object representing the component’s current, resolved props.

interface ComponentPublicInstance  $props: object >

$el ​

The root DOM node that the component instance is managing.

interface ComponentPublicInstance  $el: Node | undefined >
  • For components with a single root element, $el will point to that element.
  • For components with text root, $el will point to the text node.
  • For components with multiple root nodes, $el will be the placeholder DOM node that Vue uses to keep track of the component’s position in the DOM (a text node, or a comment node in SSR hydration mode).

For consistency, it is recommended to use template refs for direct access to elements instead of relying on $el .

$options ​

The resolved component options used for instantiating the current component instance.

interface ComponentPublicInstance  $options: ComponentOptions >

It is typically used to support custom component options:

const app = createApp( customOption: 'foo', created()  console.log(this.$options.customOption) // => 'foo' > >)

$parent ​

The parent instance, if the current instance has one. It will be null for the root instance itself.

interface ComponentPublicInstance  $parent: ComponentPublicInstance | null >

$root ​

The root component instance of the current component tree. If the current instance has no parents this value will be itself.

interface ComponentPublicInstance  $root: ComponentPublicInstance >

$slots ​

An object representing the slots passed by the parent component.

interface ComponentPublicInstance  $slots:  [name: string]: Slot > > type Slot = (. args: any[]) => VNode[]

$refs ​

An object of DOM elements and component instances, registered via template refs.

interface ComponentPublicInstance  $refs:  [name: string]: Element | ComponentPublicInstance | null > >

$attrs ​

An object that contains the component’s fallthrough attributes.

interface ComponentPublicInstance  $attrs: object >

$watch() ​

Imperative API for creating watchers.

interface ComponentPublicInstance  $watch( source: string | (() => any), callback: WatchCallback, options?: WatchOptions ): StopHandle > type WatchCallbackT> = ( value: T, oldValue: T, onCleanup: (cleanupFn: () => void) => void ) => void interface WatchOptions  immediate?: boolean // default: false deep?: boolean // default: false flush?: 'pre' | 'post' | 'sync' // default: 'pre' onTrack?: (event: DebuggerEvent) => void onTrigger?: (event: DebuggerEvent) => void > type StopHandle = () => void
  • immediate : trigger the callback immediately on watcher creation. Old value will be undefined on the first call.
  • deep : force deep traversal of the source if it is an object, so that the callback fires on deep mutations. See Deep Watchers.
  • flush : adjust the callback’s flush timing. See Callback Flush Timing and watchEffect() .
  • onTrack / onTrigger : debug the watcher’s dependencies. See Watcher Debugging.
this.$watch('a.b', (newVal, oldVal) => <>)
this.$watch( // every time the expression `this.a + this.b` yields // a different result, the handler will be called. // It's as if we were watching a computed property // without defining the computed property itself. () => this.a + this.b, (newVal, oldVal) => <> )
const unwatch = this.$watch('a', cb) // later.  unwatch()

$emit() ​

Trigger a custom event on the current instance. Any additional arguments will be passed into the listener’s callback function.

interface ComponentPublicInstance  $emit(event: string, . args: any[]): void >
export default  created()  // only event this.$emit('foo') // with additional arguments this.$emit('bar', 1, 2, 3) > >

$forceUpdate() ​

Force the component instance to re-render.

interface ComponentPublicInstance  $forceUpdate(): void >

$nextTick() ​

Instance-bound version of the global nextTick() .

interface ComponentPublicInstance  $nextTick(callback?: (this: ComponentPublicInstance) => void): Promisevoid> >

Источник

# Ссылки на элементы в шаблоне

Подразумевается, что уже изучили и разобрались с разделом Основы компонентов. Если нет — прочитайте его сначала.

Несмотря на существование входных параметров и событий, иногда может потребоваться прямой доступ к дочернему компоненту в JavaScript. Для этого можно через атрибут ref присвоить специальный ID ссылки дочернему компоненту или HTML-элементу. Например:

Это пригодится, например, когда требуется программно перевести фокус на поле ввода при монтировании компонента:

const app = Vue.createApp(>) app.component('base-input',  template: ` input ref="input" /> `, mounted()  this.focusInput() >, methods:  focusInput()  this.$refs.input.focus() > > >) 

Можно добавить другой ref и на сам компонент, чтобы использовать его для вызова метода focusInput из родительского компонента:

base-input ref="usernameInput">base-input> 
this.$refs.usernameInput.focusInput() 

Ссылки в $refs регистрируются после отрисовки компонента. Они предназначены только для исключительных случаев, когда дочерними элементами необходимо управлять напрямую — следует избегать доступа к $refs в шаблоне или вычисляемых свойствах.

(opens new window)
Последнее обновление страницы: около 2 лет назад

Источник

Читайте также:  Понятие элемент языка html
Оцените статью