1. 在 vue3 中创建方法的三种方式和获取当前 dom 元素
在setup函数中通过return暴露的函数可在模板中使用
<template>
<div @click="f1(1, $event)">methods f1</div>
<div @click="f2(2, $event)">methods f2</div>
<div @click="f3(2, $event)">methods f3</div>
</template>
<script>
export default {
setup() {
// 1. 函数声明方式
function f1(v, e) {
console.log(v)
console.log(e.target)
e.target.innerText = e.target.innerText + '1'
}
// 2. 函数表达式方式
const f2 = function (v, e) {
console.log(v)
console.log(e.target)
e.target.innerText = e.target.innerText + '2'
}
// 3. 箭头函数方式
const f3 = (v, e) => {
console.log(v)
console.log(e.target)
e.target.innerText = e.target.innerText + '3'
}
return { f1, f2, f3 }
}
}
</script>
2. 在 vue3 中获取目标 dom 元素
- 模板中 ref 属性的值必须和定义的 ref(null) 变量名相同,通过 .value 获取目标 dom 元素
- 通过ref获取dom的时机必须在dom生成之后,如果初始化获取,需要在onMounted()生命周期中获取,不可再setup函数中直接获取,否则结果为null
<template>
<h1 ref="xxx">target document</h1>
<button @click="fn">get target dom</button>
</template>
<script>
import { ref } from 'vue'
export default {
setup() {
const xxx = ref(null)
const fn = () => {
console.log(xxx)
console.log(xxx.value)
xxx.value.innerText = xxx.value.innerText + '1'
}
return { xxx, fn }
}
}
</script>
网友评论