【问题标题】:bootstrap-vue formatter is changing input positionbootstrap-vue 格式化程序正在更改输入位置
【发布时间】:2020-12-29 22:57:19
【问题描述】:

我想在 bootstrap-vue 的文件名输入中用下划线 _ 替换空格。但是如果我不在输入末尾添加一个空格,那么格式化程序会将光标位置移动到输入末尾。 如何在不改变光标位置的情况下替换空格?

我试过了:

<div class="form-group row">
    <label class="col-6 col-md-4 col-lg-3 col-xl-3">File name</label>
    <div class="col-6 col-md-8 col-lg-9 col-xl-9">
        <b-input-group v-if="viewModel.offer">
            <b-form-input ref="fileName" type="text" :formatter="formatter"></b-form-input>
            <b-input-group-append>
                <b-button variant="dark" v-b-popover.hover.top="'Download'" v-on:click=".."><i class="fas fa-arrow-circle-down"></i></b-button>
            </b-input-group-append>
        </b-input-group>
    </div>
</div>

与:

            formatter(value, event) {                
                const pos = event.target.selectionStart - 1
                const nfileName = value.replace(/\s+/g, '_');
                if (nfileName !== value) {
                    this.$nextTick(() => {
                        event.target.selectionEnd = pos
                    })
                }
                return nfileName;
            }

但是 selectionStart 的值等于 selectionEnd,所以实际位置是未知的。

【问题讨论】:

    标签: vue.js bootstrap-vue


    【解决方案1】:

    尝试使用setTimeout 而不是$nextTicksetTimeout,应该在输入被允许呈现新值(并移动光标)之后运行。

    我个人觉得这个解释很好,关于逻辑如何运作。 http://www.hesselinkwebdesign.nl/2019/nexttick-vs-settimeout-in-vue/

    new Vue({
      el: '#app',
      data() {
        return {
          text: ''
        }
      },
      methods: {
        formatter(value, event) {
          const {
            target: {
              selectionEnd,
              selectionStart
            }
          } = event
    
          setTimeout(() => {
            event.target.selectionStart = selectionStart;
            event.target.selectionEnd = selectionEnd;
          })
    
          return value.replace(/\s+/g, '_');
        }
      }
    })
    <link href="https://unpkg.com/bootstrap@4.5.2/dist/css/bootstrap.min.css" rel="stylesheet" />
    <link href="https://unpkg.com/bootstrap-vue@2.16.0/dist/bootstrap-vue.css" rel="stylesheet" />
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.js"></script>
    <script src="https://unpkg.com/bootstrap-vue@2.16.0/dist/bootstrap-vue.js"></script>
    
    <div id="app">
      <b-input v-model="text" :formatter="formatter"></b-input>
    </div>

    【讨论】:

      猜你喜欢
      • 2020-09-01
      • 1970-01-01
      • 2021-07-25
      • 1970-01-01
      • 2020-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-04
      相关资源
      最近更新 更多