当前位置: 移动技术网 > IT编程>开发语言>JavaScript > vue获取input焦点,弹框后自动获取input焦点

vue获取input焦点,弹框后自动获取input焦点

2020年04月11日  | 移动技术网IT编程  | 我要评论
<!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>

  

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网