zoukankan      html  css  js  c++  java
  • vue中ref的用法总结

    之前在用这个属性的时候,就是觉得他基本用在表单或者子组件上,方便方法的调用,查资料之后,才明白更多。

    基本用法,本页面获取dom元素

    <template>
      <div id="app">
        <div ref="testDom">11111</div>
        <button @click="getTest">获取test节点</button>
      </div>
    </template>
    
    <script>
    export default {
      methods: {
        getTest() {
          console.log(this.$refs.testDom)
        }
      }
    };
    </script>

    this.$refs.testDom.style.color = "blue"

     然后就是我所说的,就是可以拿到子组件中的data和去调用子组件中的方法

    调用子组件中的data

    子组件:

    <template>
      <div>
          {{ msg }}
      </div>
    </template>
    
    <script>
    export default {
      data() {
        return {
          msg: "hello world"
        }
      }
    }
    </script>
    父组件:
    <template>
      <div id="app">
        <HelloWorld ref="hello"/>
        <button @click="getHello">获取helloworld组件中的值</button>
      </div>
    </template>
    
    <script>
    import HelloWorld from "./components/HelloWorld.vue";
    
    export default {
      components: {
        HelloWorld
      },
      data() {
        return {}
      },
      methods: {
        getHello() {
          console.log(this.$refs.hello.msg)
        }
      }
    };
    </script>

    调用子组件中的方法

    子组件:

    <template>
      <div>
      </div>
    </template>
    
    <script>
    export default {
      methods: {
        open() {
          console.log("调用到了")
        }
      }
    }
    </script>
    父组件:
    <template>
      <div id="app">
        <HelloWorld ref="hello"/>
        <button @click="getHello">获取helloworld组件中的值</button>
      </div>
    </template>
    
    <script>
    import HelloWorld from "./components/HelloWorld.vue";
    
    export default {
      components: {
        HelloWorld
      },
      data() {
        return {}
      },
      methods: {
        getHello() {
          this.$refs.hello.open();
        }
      }
    };
    </script>

     
  • 相关阅读:
    计算机网络
    二叉树
    队列
    百度脑图-离线版(支持Linux、Mac、Win)
    nested exception is java.lang.NoClassDefFoundError: javax/xml/soap/SOAPElement
    手写注解实现SpringMVC底层原理(虽简单却五脏俱全《注重思路》)
    java异常
    JVM相关
    redis相关总结
    mysql 数据库相关
  • 原文地址:https://www.cnblogs.com/zhilu/p/13793028.html
Copyright © 2011-2022 走看看