<!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>

  

内容来源于网络如有侵权请私信删除
你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!

相关课程