zoukankan      html  css  js  c++  java
  • vue之ref

      ref 被用来给元素或子组件注册引用信息。引用信息将会注册在父组件的 $refs 对象上。如果在普通的 DOM 元素上使用,引用指向的就是 DOM 元素;如果用在子组件上,引用就指向组件。

    1、ref用在普通DOM元素

    • 在html标签上加上ref属性
    <div id="app">
        <input type="text" ref="input1"/>
    </div>
    • 通过this.$refs.标签的ref的名来获取dom元素
    <script>
        new Vue({
          el:'#app',
          data:{
          },
          method:{
    
          },
          mounted(){
            //dom元素加载完毕
            console.log('ref',this.$refs.input1) //获取dom元素 <input type="text">
            this.$refs.input1.focus()
          }
        })
    
    </script>

    2、ref用在组件中

    • 注册全局组件c1
    <script>
        //注册全局组件
      Vue.component('c1', {
        data:function () {
            return {}
        },
        template:`<h1>我是测试组件c1</h1>`
    
      })
        new Vue({
          el:'#app',
          mounted(){
            //dom元素加载完毕
            console.log('ref',this.$refs.c1) //获取组件c1实例 <input type="text">
            console.log(this.$refs) //获取的是所有带ref属性的组件或者dom标签的字典{input1: input, c1: VueComponent}
            
            for (let key in this.$refs) //使用for in 循环字典
                console.log(this.$refs[key])
          }
        })
    
    </script>
    • 在html中使用全局组件
    <div id="app">
        <input type="text" ref="input1"/>
    
        <!--使用全局组件-->
        <c1 ref="c1"></c1>
    </div>
  • 相关阅读:
    507.Perfect Number
    441.Arranging Coins
    344.Reverse String
    160.Intersection of Two Linked Lists
    HDU-2521 反素数
    HDU-2710 Max Factor
    HDU-2552 三足鼎立
    HDU-2549 壮志难酬
    HDU-2548 两军交锋
    HDU-2550 百步穿杨
  • 原文地址:https://www.cnblogs.com/shenjianping/p/11462282.html
Copyright © 2011-2022 走看看