下邊代碼的目的是用自定義指令實現(xiàn)組件中input輸入框的自動聚焦
在main.js中定義全局自定義指令
//全局創(chuàng)建自定義指令
Vue.directive('fofo',{
? inserted(el){
// 因為使用的是vant2的Search組件,它里邊有很多元素,所以要找到input標(biāo)簽
? ? let theInput = el.querySelector('input')
? ? theInput.focus()
? }
})
在頁面中使用指令
<van-search placeholder="請輸入搜索關(guān)鍵詞" background="#007BFF" shape="round" v-fofo/>
在main.js中封裝中間件函數(shù)插件
實現(xiàn)的效果也是輸入框自動聚焦
const directiveObj={
? install(Vue){
? ? Vue.directive('fofo',{
? ? ? inserted(el){
? ? ? ? let theInput = el.querySelector('input')
? ? ? ? theInput.focus()
? ? ? }
? ? })
? }
}
Vue.use(directiveObj)