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

    一、转载声明

    本文非原创,转载自 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" 来改变dom的样式

    三、获取子组件中的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>

    控制台输出如下:

    学习和码字过程难免出现疏漏,欢迎指正!QQ:1801888312
  • 相关阅读:
    【转】CUDA5/CentOS6.4
    【转】centos 6.4 samba 安装配置
    【转】Install MATLAB 2013a on CentOS 6.4 x64 with mode silent
    【转】Getting xrdp to work on CentOS 6.4
    【VLFeat】使用matlab版本计算HOG
    Unofficial Windows Binaries for Python Extension Packages
    March 06th, 2018 Week 10th Tuesday
    March 05th, 2018 Week 10th Monday
    March 04th, 2018 Week 10th Sunday
    March 03rd, 2018 Week 9th Saturday
  • 原文地址:https://www.cnblogs.com/liuguo/p/14428945.html
Copyright © 2011-2022 走看看