解决微信小程序弹出层中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')
    }
  }
posted @ 2020-12-21 18:56  Monday1997  阅读(2410)  评论(1编辑  收藏  举报