vue3中ref使用
时间: 2023-12-07 11:39:27 浏览: 77
在Vue 3中,ref函数可以用于处理响应式数据,也可以用于访问组件中的DOM元素、组件实例以及存储任何需要在组件中进行状态管理的值。下面是一些ref函数的用法:
1.处理响应式数据
```vue
<template>
<div>{{ count.value }}</div>
</template>
<script>
import { ref } from 'vue'
export default {
setup() {
const count = ref(0)
return {
count
}
}
}
</script>
```***```vue
<template>
<div>
<button ref="myButton" @click="handleClick">Click me</button>
</div>
</template>
<script>
import { ref } from 'vue'
export default {
setup() {
const myButton = ref(null)
const handleClick = () => {
myButton.value.innerText = 'Button clicked'
}
return {
myButton,
handleClick
}
}
}
</script>
```
3.访问组件实例
```vue
<template>
<div>
<ChildComponent ref="childComponent" />
</div>
</template>
<script>
import { ref } from 'vue'
import ChildComponent from './ChildComponent.vue'
export default {
components: {
ChildComponent
},
setup() {
const childComponent = ref(null)
const handleClick = () => {
childComponent.value.doSomething()
}
return {
childComponent,
handleClick
}
}
}
</script>
```
4.存储任何需要在组件中进行状态管理的值
```vue
<template>
<div>{{ message.value }}</div>
</template>
<script>
import { ref } from 'vue'
export default {
setup() {
const message = ref('Hello, world!')
const setMessage = (newMessage) => {
message.value = newMessage
}
return {
message,
setMessage
}
}
}
</script>
```
阅读全文