Home > Web Front-end > Vue.js > How to get nodes in vue

How to get nodes in vue

下次还敢
Release: 2024-05-02 21:45:39
Original
1097 people have browsed it

Methods to get nodes in Vue: Directly access DOM nodes: Use $el to access the component root element. Use $refs: To access the child elements or root elements of the component, you need to use ref to specify the name. Use the render function: Create the element in the render function and access the DOM node through vm.$vnode. Using third-party libraries: such as Vuetify and Element UI, DOM nodes can be accessed through $el and $refs respectively.

How to get nodes in vue

#How to get nodes in Vue?

Direct access to DOM nodes

  • $el: Access the component root element.
  • $refs: To access the child elements or root elements of the component, you need to specify the name using the ref attribute in the template.

Use the rendering function

  • In the render function, use the createElement function to create the element, and returns it as v-node.
  • Then you can access v-node through vm.$vnode to obtain the DOM node.

Use third-party libraries

  • Vuetify: Provides $el attributes, which can be passed this.$ el Access DOM nodes.
  • Element UI: Provides the $refs attribute, which can access DOM nodes through this.$refs.

Example:

  • Direct access to DOM node:

    <code class="html"><template>
    <div id="app">Hello</div>
    </template>
    
    <script>
    export default {
    mounted() {
      console.log(this.$el); // 获取 DOM 节点 <div id="app">
    }
    }
    </script></code>
    Copy after login
  • Use rendering function:

    <code class="html"><template>
    <div>Hello</div>
    </template>
    
    <script>
    export default {
    render(h) {
      return h('div', 'Hello');
    },
    mounted() {
      console.log(this.$vnode.elm); // 获取 DOM 节点 <div>
    }
    }
    </script></code>
    Copy after login
  • Use third-party library:

    <code class="html"><template>
    <v-btn ref="button" @click="handleClick">Button</v-btn>
    </template>
    
    <script>
    import { Button } from 'vuetify';
    
    export default {
    components: { Button },
    methods: {
      handleClick() {
        console.log(this.$refs.button); // 获取 DOM 节点 <button>
      }
    }
    }
    </script></code>
    Copy after login

The above is the detailed content of How to get nodes in vue. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
vue
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template