Vue3.0中ref的使用

单个ref:

<template> 
  <div ref="root">This is a root element</div>
</template>

<script>
  import { ref, onMounted } from 'vue'

  export default {
    setup() {
      const root = ref(null)

      onMounted(() => {
        console.log(root.value) 
      })

      return {
        root
      }
    }
  }
</script>

多个ref

<template>
  <div v-for="(item, i) in arr"  :key="i" :ref="setRef" >
    {{ item }}
  </div>
</template>

<script>
  import { ref, nextTick } from 'vue'

  export default {
    setup() {
      const arr = ref([1, 2, 3])
    		const myRef = ref([])

    	const setRef = (el) => {
      nextTick(() => {
        console.log(el.getBoundingClientRect().top)
      })
      myRef.value.push(el.getBoundingClientRect().top)
    	}

      return {
        arr,
        setRef
      }
    }
  }
</script>
vuejs
64 views
Comments
登录后评论
Sign In