Vue中ref和$refs的介绍及使用

       在JavaScript中需要通过document.querySelector("#demo")来获取dom节点,然后再获取这个节点的值。在Vue中,我们不用获取dom节点,元素绑定ref之后,直接通过this.$refs即可调用,这样可以减少获取dom节点的消耗。

ref介绍

ref被用来给元素或子组件注册引用信息。引用信息将会注册在父组件的 $refs对象上。如果在普通的 DOM 元素上使用,引用指向的就是 DOM 元素;如果用在子组件上,引用就指向该子组件实例

通俗的讲,ref特性就是为元素或子组件赋予一个ID引用,通过this.$refs.refName来访问元素或子组件的实例


  
  
  1. <p ref="p">Hello </p>
  2. <children ref="children"> </children>

  
  
  1. this.$refs.p
  2. this.$refs.children

this.$refs介绍

this.$refs是一个对象,持有当前组件中注册过 ref特性的所有 DOM 元素和子组件实例

注意: $refs只有在组件渲染完成后才填充,在初始渲染的时候不能访问它们,并且它是非响应式的,因此不能用它在模板中做数据绑定

注意:

当ref和v-for一起使用时,获取到的引用将会是一个数组,包含循环数组源


  
  
  1. <template>
  2. <div>
  3. <div ref="myDiv" v-for="(item, index) in arr" :key="index">{{item}} </div>
  4. </div>
  5. </template>
  6. <script>
  7. export default {
  8. data() {
  9. return {
  10. arr: [ 'one', 'two', 'three', 'four']
  11. }
  12. },
  13. mounted() {
  14. console.log( this.$refs.myDiv)
  15. },
  16. methods: {}
  17. }
  18. </script>
  19. <style lang="sass" scoped>
  20. </style>

实例(通过ref特性调用子组件的方法)

【1】子组件code:


  
  
  1. <template>
  2. <div>{{msg}} </div>
  3. </template>
  4. <script>
  5. export default {
  6. data() {
  7. return {
  8. msg: '我是子组件'
  9. }
  10. },
  11. methods: {
  12. changeMsg() {
  13. this.msg = '变身'
  14. }
  15. }
  16. }
  17. </script>
  18. <style lang="sass" scoped> </style>

【2】父组件code:


  
  
  1. <template>
  2. <div @click="parentMethod">
  3. <children ref="children"> </children>
  4. </div>
  5. </template>
  6. <script>
  7. import children from 'components/children.vue'
  8. export default {
  9. components: {
  10. children
  11. },
  12. data() {
  13. return {}
  14. },
  15. methods: {
  16. parentMethod() {
  17. this.$refs.children //返回一个对象
  18. this.$refs.children.changeMsg() // 调用children的changeMsg方法
  19. }
  20. }
  21. }
  22. </script>
  23. <style lang="sass" scoped> </style>

       在JavaScript中需要通过document.querySelector("#demo")来获取dom节点,然后再获取这个节点的值。在Vue中,我们不用获取dom节点,元素绑定ref之后,直接通过this.$refs即可调用,这样可以减少获取dom节点的消耗。

猜你喜欢

转载自blog.csdn.net/WXB_gege/article/details/106930168