$refs = ref/$refs; $nextTick = ref/$refs
Gets a node or component instance. Scenario: Simply get properties or methods of a node or component instance without changing its data. Bug: must be done after template rendering, not reactive, with $nextTick from time to time.
Ref in different positions has different effects:
- Node can pass
this.$refs.p
Gets the properties or methods of the node, such as<p ref="p">hello</p>
- Component can be passed
this.$refs.child
Get the corresponding component instance to get the properties and methods on the component, such as<child-component ref="child"></child-component>
- V-for syntax can be passed
this.$refs.items
Get an array of node or component instances, specific to one item, as requiredthis.$refs.items[index]
, such as<item ref="items" v-for=".">hello</item>
Ref does not take effect until the component has been rendered
Ref exists as an attribute on the tag, so it doesn’t take effect until the component is rendered. Therefore $refs is not reactive, avoid accessing $refs in templates or computed properties.
Here’s an example:
<template lang="pug"> div list-item(ref="listItem1") list-item(v-if="isShow" ref="listItem2") </template> <script> import ListItem from "@/components/ListItem"; export default { components: { ListItem }, data:() => ({ isShow: ""}), created () {/ / the template does not render / / {} the console log (1, enclosing $refs); }, mounted() {// isShow is false, listItem1:{// listItem2 :{... } } console.log(2, this.$refs); setTimeout(() => { this.isShow = true; // {listItem1:{... } } console.log(3, this.$refs); This. $nextTick (() = > {/ / only after the template updating / / {listItem1: {... },listItem1:{... } } console.log(4, this.$refs); }); }, 500); }}; </script>Copy the code
created
The time,$refs
It’s just an empty object.mounted
The time,$refs
Data is available, but nodes or components that are not rendered are still not available- A node or component,
v-if
The value of thefalse=>true
Because the template has not been updated, so still can not get - Often with
nextTick
reference
- Official website: Access child component instances or child elements
- Official Api: special attribute ref