1. 程式人生 > 實用技巧 >解決微信小程式彈出層中input無法聚焦的問題

解決微信小程式彈出層中input無法聚焦的問題

此處使用的是vant框架

解決聚焦問題

這裡遇到的問題是,在點選搜尋框後,設定了彈起的彈出層中van-search 的foucs值為true

但是沒有起到聚焦效果

原因在於彈出框帶有一個動畫效果,需要在動畫效果之後再使focus的值為true才能生效

關鍵程式碼如下

<van-search  
          focus="{{isfocus}}"
          model:value="{{ searchValue }}" 
          placeholder="請輸入您要搜尋的值" 
          />

js中

 lifetimes: {
    attached: function() {
       setTimeout(()=>{
        this.setData({
          isfocus:true
        })
      },800)
    }
  },

順便記錄下封裝元件遇到的一些問題

需要先將json中設定"component":true

js的Component中設定options 這是為了可以使用父元件中的樣式

 options:{
    styleIsolation:"shared"
  },

當封裝彈出框元件時(vue同樣適用)

子元件設定一個properties接收父元件傳來的值fromparents

再設定一個data:isDialogShow,監測fromparents值的變化並賦值給這個data

不直接賦予是因為properties是單向資料流,只能父元件改變子元件,而不能子元件改變父元件,所以需要一個值作為中間過渡

父元件

html

 <component-popup  binddialogClose="dialogClose" fromparents="{{showDialog}}"/>

主要事件程式碼如下

dialogClose(){
    setTimeout(()=>{  //因為動畫原因加的延時
      this.setData({
        showDialog: false
      });
    },500)
  },

子元件

html

<van-popup show="{{ isDialogShow }}" position="bottom" round custom-style="height: 94%;" bind:close="onClose">

js

主要程式碼如下

  observers:{
    'fromparents'(){
      this.setData({
        isDialogShow:this.data.fromparents
      })
     if(this.data.showDialog){
        setTimeout(()=>{
          this.setData({
            isfocus:true
          })
        },800)
      } 
    }
  },
 methods:{
    // 關閉彈窗時
    onClose() {
      this.triggerEvent('dialogClose')
    }
  }