浅谈Vue.js中ref ($refs)用法举例总结

本文介绍了Vue.js中ref ($refs)用法举例总结,分享给大家,具体如下:

看Vue.js文档中的ref部分,自己总结了下ref的使用方法以便后面查阅。

一、ref使用在外面的组件上

HTML 部分

<div id=\"ref-outside-component\" v-on:click=\"consoleRef\">
  <component-father ref=\"outsideComponentRef\">
  </component-father>
  <p>ref在外面的组件上</p>
</div>

js部分

  var refoutsidecomponentTem={
    template:\"<div class=\'childComp\'><h5>我是子组件</h5></div>\"
  };
  var refoutsidecomponent=new Vue({
    el:\"#ref-outside-component\",
    components:{
      \"component-father\":refoutsidecomponentTem
    },
    methods:{
      consoleRef:function () {
        console.log(this); // #ref-outside-component   vue实例
        console.log(this.$refs.outsideComponentRef); // div.childComp vue实例
      }
    }
  });

二、ref使用在外面的元素上

HTML部分

<!--ref在外面的元素上-->
<div id=\"ref-outside-dom\" v-on:click=\"consoleRef\" >
  <component-father>
  </component-father>
  <p ref=\"outsideDomRef\">ref在外面的元素上</p>
</div>

JS部分

  var refoutsidedomTem={
    template:\"<div class=\'childComp\'><h5>我是子组件</h5></div>\"
  };
  var refoutsidedom=new Vue({
    el:\"#ref-outside-dom\",
    components:{
      \"component-father\":refoutsidedomTem
    },
    methods:{
      consoleRef:function () {
        console.log(this); // #ref-outside-dom  vue实例
        console.log(this.$refs.outsideDomRef); //  <p> ref在外面的元素上</p>
      }
    }
  });

三、ref使用在里面的元素上—局部注册组件

HTML部分

<!--ref在里面的元素上-->
<div id=\"ref-inside-dom\">
  <component-father>
  </component-father>
  <p>ref在里面的元素上</p>
</div>

JS部分

  var refinsidedomTem={
    template:\"<div class=\'childComp\' v-on:click=\'consoleRef\'>\" +
            \"<h5 ref=\'insideDomRef\'>我是子组件</h5>\" +
         \"</div>\",
    methods:{
      consoleRef:function () {
        console.log(this); // div.childComp  vue实例 
        console.log(this.$refs.insideDomRef); // <h5 >我是子组件</h5>
      }
    }
  };
  var refinsidedom=new Vue({
    el:\"#ref-inside-dom\",
    components:{
      \"component-father\":refinsidedomTem
    }
  });

四、ref使用在里面的元素上—全局注册组件

HTML部分

<!--ref在里面的元素上--全局注册-->
<div id=\"ref-inside-dom-all\">
  <ref-inside-dom-quanjv></ref-inside-dom-quanjv>
</div>

JS部分

  Vue.component(\"ref-inside-dom-quanjv\",{
    template:\"<div class=\'insideFather\'> \" +
          \"<input type=\'text\' ref=\'insideDomRefAll\' v-on:input=\'showinsideDomRef\'>\" +
          \" <p>ref在里面的元素上--全局注册 </p> \" +
         \"</div>\",
    methods:{
      showinsideDomRef:function () {
        console.log(this); //这里的this其实还是div.insideFather
        console.log(this.$refs.insideDomRefAll); // <input type=\"text\">
      }
    }
  });

  var refinsidedomall=new Vue({
    el:\"#ref-inside-dom-all\"
  });

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容