vue中的ref是用来获取、操作dom或者组件的属性
(1)Vue3中操作单个DOM元素
ref操作单个DOM或者组件的流程
1、定义一个响应式变量
2、把变量返回给模板使用
3、模板中绑定上述返回的数据
4、可以通过变量操作DOM或者组件实例
<template>
<div>
<div>ref操作DOM和组件</div>
<hr>
<!-- 3、模板中绑定上述返回的数据 -->
<div ref='info'>hello</div>
<!-- <my-com ref='info'>hello</my-com> -->
<ul>
<li ref='fruit' v-for='item in fruits' :key='item.id'>{{item.name}}</li>
</ul>
<button @click='handleClick'>点击</button>
</div>
</template>
<script>
import { ref } from 'vue'
export default {
name: 'App',
setup () {
// vue2中这样使用ref
// this.$refs.info.innerHTML
// this.$refs.fruit 的值应该是一个数组,数组中放的DOM元素
// this.$refs.fruit[0].innerHTML ---> apple
// -----------------------------------------
// Vue3中通过ref操作DOM
// 1、定义一个响应式变量
const info = ref(null)
const fruits = ref([{
id: 1,
name: 'apple'
}, {
id: 2,
name: 'orange'
}])
const handleClick = () => {
// 4、此时可以通过info变量操作DOM
console.log(info.value.innerHTML)
}
// 2、把变量返回给模板使用
return { fruits, info, handleClick }
}
}
</script>
<style lang="less">
</style>
(2)ref批量操作信息
ref批量操作元素的流程
1、定义一个函数
2、把该函数绑定到ref上(必须得动态绑定)
3、在函数中可以通过参数得到单个元素,这个元素一般可以放到数组中
4、通过上述数组即可操作批量的元素
<template>
<div>
<div>ref操作DOM和组件</div>
<hr>
<!-- 3、模板中绑定上述返回的数据 -->
<div ref='info'>hello</div>
<!-- <my-com ref='info'>hello</my-com> -->
<ul>
<li :ref='setFruits' v-for='item in fruits' :key='item.id'>{{item.name}}</li>
</ul>
<button @click='handleClick'>点击</button>
</div>
</template>
<script>
import { ref } from 'vue'
export default {
name: 'App',
setup () {
// this.$refs.info.innerHTML
// this.$refs.fruit 的值应该是一个数组,数组中放的DOM元素
// this.$refs.fruit[0].innerHTML ---> apple
// -----------------------------------------
// Vue3中通过ref操作DOM
// 1、定义一个响应式变量
const info = ref(null)
const fruits = ref([{
id: 1,
name: 'apple'
}, {
id: 2,
name: 'orange'
}, {
id: 3,
name: 'pineapple'
}])
// 定义操作DOM的函数
const arr = []
const setFruits = (el) => {
// 参数el表示单个DOM元素
arr.push(el)
}
const handleClick = () => {
// 4、此时可以通过info变量操作DOM
// console.log(info.value.innerHTML)
console.log(arr)
}
// 2、把变量返回给模板使用
return { fruits, info, handleClick, setFruits }
}
}
</script>
<style lang="less">
</style>