当前位置:   article > 正文

Vue ref访问这些元素或组件的实例

Vue ref访问这些元素或组件的实例

可以在任意DOM元素上使用ref属性,然后在Vue实例中通过this.$refs访问这个DOM元素 

 1.访问子组件实例,可以调用方法或者获取值

  1. <template>
  2. <div>
  3. <input type="text" ref="myInput" />
  4. <button @click="focusInput">聚焦输入框</button>
  5. </div>
  6. </template>
  7. <script>
  8. export default {
  9. methods: {
  10. focusInput() {
  11. this.$refs.myInput.focus(); // 让输入框获得焦点
  12. }
  13. }
  14. };
  15. </script>

 2.访问子组件实例,可以调用方法或者获取值

  1. template>
  2. <ChildComponent ref="childRef" />
  3. </template>
  4. <script>
  5. import ChildComponent from './ChildComponent.vue';
  6. export default {
  7. methods: {
  8. callChildMethod() {
  9. this.$refs.childRef.someMethod(); // 调用子组件的方法
  10. this.$refs.childRef.name; // 获取子组件的数据
  11. }
  12. }
  13. };
  14. </script>

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/633117
推荐阅读
相关标签
  

闽ICP备14008679号