当前位置: 移动技术网 > IT编程>脚本编程>vue.js > Vue中$refs的用法详解

Vue中$refs的用法详解

2018年08月06日  | 移动技术网IT编程  | 我要评论

早泄宁,血祭的冷护法之恋,纪念抗战70周年手抄报

说明:vm.$refs 一个对象,持有已注册过 ref 的所有子组件(或html元素)

使用:在 html元素 中,添加ref属性,然后在js中通过vm.$refs.属性来获取

注意:如果获取的是一个子组件,那么通过ref就能获取到子组件中的data和methods

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>document</title>
  <!-- <script type="text/javascript" src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script> -->
  <script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
  <style>
  </style>
</head>
<body>
  <div id="vue_app">
    <qinwm ref="vue_qinwm"></qinwm>
    <p ref="vue_p">hello, world!</p>
    <button @click="getref">getref</button>
  </div>
</body>
</html>
<script>
  vue.component("qinwm", {
    template: `<h1>{{msg}}</h1>`,
    data(){
      return {
        msg: "hello, world!"
      };
    },
    methods:{
      func:function (){
        console.log("func!");
      }
    }
  });
  new vue({
    el: "#vue_app",
    data(){
      return {};
    },
    methods: {
      getref () {
        console.log(this.$refs);
        console.log(this.$refs.vue_p); // <p>hello, world!</p>
        console.log(this.$refs.vue_qinwm.msg); // hello, world!
        console.log(this.$refs.vue_qinwm.func); // func:function (){ console.log("func!"); }
        this.$refs.vue_qinwm.func(); // func!
      }
    }
  });
</script>

总结

以上所述是小编给大家介绍的vue中$refs的用法详解,希望对大家有所帮助

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网