常规用法
<template>
<div class="search-input">
<input type="text" ref="searchInputElem" v-model="searchValue" @keyup.enter="onSearch" placeholder="输入关键词" /> <!-- 【step1】dom层定义ref="searchInputElem" -->
</div>
</template>
<script>
import { onMounted, reactive, toRefs, ref } from "vue";
export default {
setup() {
const state = reactive({
searchValue: ""
});
function onSearch(){ ... }
const searchInputElem = ref(null) //【step2】定义searchInputElem 【注意】:这里定义的searchInputElem必须和dom层里定义的ref="searchInputElem"保持一致
onMounted(()=>{
console.log(searchInputElem.value) //【step4】:获取元素,注意需要在元素加载出来后才能获取,比如可在onMounted生命周期或者nextTick中使用
searchInputElem.value.focus()
})
return {
onSearch,
searchInputElem, // 【step3】注意:必须return出来
...toRefs(state),
};
},
};
</script>
基于自己代码风格的写法
<template>
<div class="search-input">
<input type="text" ref="searchInputElem" v-model="searchValue" @keyup.enter="onSearch" placeholder="输入关键词" /> <!-- 【step1】dom层定义ref="searchInputElem" -->
</div>
</template>
<script>
import { onMounted, reactive, toRefs, ref } from "vue";
export default {
setup() {
const state = reactive({
searchValue: "",
searchInputElem: null //【step2】定义searchInputElem 【注意】:这里定义的searchInputElem必须和dom层里定义的ref="searchInputElem"保持一致
});
function onSearch(){ ... }
onMounted(()=>{
console.log(state.searchInputElem) //【step4】:获取元素,注意需要在元素加载出来后才能获取,比如可在onMounted生命周期或者nextTick中使用
state.searchInputElem.focus()
})
return {
onSearch,
...toRefs(state), // 【step3】注意:必须return出来
};
},
};
</script>
标签:...,vue3,onMounted,reactive,state,searchInputElem,注意事项,ref
From: https://www.cnblogs.com/huihuihero/p/16931598.html