ref多种使用场景

73 阅读1分钟

ref

  1. 访问 DOM 元素
<template>
 
  <div>
 
    <input ref="myInput" type="text">
 
    <button @click="focusInput">Focus Input</button>
 
  </div>
 
</template>
 
 
 
<script>
 
import { ref } from 'vue'
 
 
 
export default {
 
  setup() {
 
    const myInput = ref(null)
 
 
 
    function focusInput() {
 
      myInput.value.focus()
 
    }
 
 
 
    return {
 
      myInput,
 
      focusInput
 
    }
 
  }
 
}
 
</script>

  1. 访问组件实例
<template>
 
  <div>
 
    <Child ref="childComponent" />
 
    <button @click="callChildMethod">Call Child Method</button>
 
  </div>
 
</template>
 
 
 
<script>
 
import Child from './Child.vue'
 
 
 
export default {
 
  components: {
 
    Child
 
  },
 
  setup() {
 
    const childComponent = ref(null)
 
 
 
    function callChildMethod() {
 
      childComponent.value.myMethod()
 
    }
 
 
 
    return {
 
      childComponent,
 
      callChildMethod
 
    }
 
  }
 
}
 
</script>

3. vue3中的初始化定义状态管理的值

<template>
 
  <div>
 
    <p v-if="isLoading">Loading...</p>
 
    <button @click="fetchData">Fetch Data</button>
 
  </div>
 
</template>
 
 
 
<script>
 
import { ref } from 'vue'
 
 
 
export default {
 
  setup() {
 
    const isLoading = ref(false)
 
    const timerId = ref(null)
 
 
 
    function fetchData() {
 
      isLoading.value = true
 
 
 
      timerId.value = setTimeout(() => {
 
        isLoading.value = false
 
        clearTimeout(timerId.value)
 
      }, 3000)
 
    }
 
 
 
    return {
 
      isLoading,
 
      fetchData
 
    }
 
  }
 
}
 
</script>

4.ref可以调用组件中的方法

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<!-- ref 加在子组件上,用this.$refs.(ref值) 获取到的是组件实例,可以使用组件的所有方法。在使用方法的时候直接this.$refs.(ref值).方法() 就可以使用了。 -->
	</head>
	<body>
		<div id="app">
			<counter ref="one" @change="handClick"></counter>
			<counter ref="two" @change="handClick"></counter>
			<h2>{{total}}</h2>
		</div>
 
		<script src="vue.js"></script>
		<script type="text/javascript">
			Vue.component("counter", {
				template: `<div @click="handClick">{{number}}</div>`,
				data() {
					return {
						number: 0,
					}
				},
				methods: {
					handClick() {
						this.number++
						this.$emit("change")
					}
				}
			})
 
			const vm = new Vue({
				el: "#app",
				data() {
					return {
						total: 0
					}
				},
				methods: {
					handClick() {
						this.total = this.$refs.one.number + this.$refs.two.number
						console.log(this.$refs);   //这里的this.$refs指的是one、two两个组件实例
					}
				}
			})
		</script>
	</body>
</html>