vue獲取input焦點,彈框後自動獲取input焦點

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <!-- 引入樣式 -->
  <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
  <!-- 引入組件庫 -->
  <script src="https://unpkg.com/element-ui/lib/index.js"></script>
</head>

<body>
  <div id="app">
    <input type="text" id="one" value="11111">
    <h2></h2>
    <input type="text" id="two" value="22222">
    <h2></h2>
    <input type="text" id="three"  value="33333" v-focus>
    <h2></h2>
    <input type="text" id="four" value="444444">
    <h2></h2>
    <el-row>
      <el-button type="primary" @click="openOne">點開彈框1</el-button>
    </el-row>
    <h2></h2>
    <el-row>
      <el-button type="primary" @click="openTwo">點開彈框2</el-button>
    </el-row>

    <!-- 第一個彈框 -->
    <el-dialog title="1111111111111" :visible.sync="dialogVisibleOne" width="80%">
      <input v-model="one"  ref="ref1" ></input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleOne = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisibleOne = false">確 定</el-button>
      </span>
    </el-dialog>

    <!-- 第2個彈框 -->
    <el-dialog title="2222222222" :visible.sync="dialogVisibleTwo" width="80%">
      <el-input v-model="two" ref="refTwo"></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleTwo = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisibleTwo = false">確 定</el-button>
      </span>
    </el-dialog>

  </div>
  <script>
    var app = new Vue({
      el: '#app',
      data() {
        return {
          id: 'ssssss',
          dialogVisibleOne: false, // 彈框顯示隱藏
          dialogVisibleTwo: false,
          one: '',
          two: ''
        }
      },
      methods: {
        /**
         * 打開第一個彈框 自動獲取焦點
        */
        openOne() {
          this.dialogVisibleOne = true // 1. 讓彈框顯示
          this.$nextTick(() => { // 2. 彈框顯示DOM更新完成後 獲取refs.ref1 設置焦點
            console.log(this.$refs.ref1)
            this.$refs.ref1.focus() // 設置焦點
          })
        },
        /**
         * 打開第二個彈框 獲取焦點
        */
        openTwo() {
          this.dialogVisibleTwo = true
          this.$nextTick(() => {
            this.$refs.refTwo.focus()
          })
        }
      },
      /**
       * 自定義指令 讓打開頁面先獲取焦點
      */
      directives: {
        focus: {
          // 指令的定義
          inserted: function (el) {
            el.focus()
          }
        }
      }
    })
  </script>
</body>

</html>

  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章