组合API-ref属性
在vue2.x
中,可以通过给元素添加ref='xxx'
属性,然后在代码中通过this.$refs.xxx
获取到对应的元素
然而在vue3
中时没有$refs
这个东西的,因此vue3
中通过ref
属性获取元素就不能按照vue2
的方式来获取。
目标:掌握使用ref属性绑定DOM或组件
获取DOM或者组件实例可以使用ref属性,写法和vue2.0需要区分开
- 基于Vue2的方式操作ref-----数组场景
<ul>
<li v-for="(item, index) in list" ref="fruits" :key="index">{
{ item }}</li>
<!-- <my-com :key='index' v-for='index in 8' ref='info'></my-com> -->
</ul>
<button @click="handleClick">点击</button>
methods: {
handleClick () {
const fruits = this.$refs.fruits
console.log(fruits[1].innerHTML)
}
}
// 批量绑定同名的ref (主要就是v-for场景中使用 ref),此时通过[this.$refs.名称]访问的值应该是一个数组,数组中包含每一个DOM元素
// ref绑定组件的用法与之类似
总结:
- Vue2中可以通过ref直接操作单个DOM和组件
this.$refs.info.innerHTML
- Vue2中可以批量通过ref操作DOM和组件
this.$refs.fruit[0].innerHTML
- ref操作单个DOM元素----Vue3的规则
<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 () {
// 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>
总结:操作单个DOM或者组件的流程
- 定义一个响应式变量
- 把变量返回给模板使用
- 模板中绑定上述返回的数据
- 可以通过info变量操作DOM或者组件实例
- 获取v-for遍历的DOM或者组件
<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>
总结:ref批量操作元素的流程
- 定义一个函数
- 把该函数绑定到ref上(必须动态绑定)
- 在函数中可以通过参数得到单个元素,这个元素一般可以放到数组中
- 通过上述数组即可操作批量的元素