vue 生命周期钩子函数 mounted()实例

在挂载后操作dom获取焦点。

XML 复制代码
<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>示例-获取焦点</title>
  <!-- 初始化样式 -->
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/reset.css@2.0.2/reset.min.css">
  <!-- 核心样式 -->
  <style>
    html,
    body {
      height: 100%;
    }
    .search-container {
      position: absolute;
      top: 30%;
      left: 50%;
      transform: translate(-50%, -50%);
      text-align: center;
    }
    .search-container .search-box {
      display: flex;
    }
    .search-container img {
      margin-bottom: 30px;
    }
    .search-container .search-box input {
      width: 512px;
      height: 16px;
      padding: 12px 16px;
      font-size: 16px;
      margin: 0;
      vertical-align: top;
      outline: 0;
      box-shadow: none;
      border-radius: 10px 0 0 10px;
      border: 2px solid #c4c7ce;
      background: #fff;
      color: #222;
      overflow: hidden;
      box-sizing: content-box;
      -webkit-tap-highlight-color: transparent;
    }
    .search-container .search-box button {
      cursor: pointer;
      width: 112px;
      height: 44px;
      line-height: 41px;
      line-height: 42px;
      background-color: #ad2a27;
      border-radius: 0 10px 10px 0;
      font-size: 17px;
      box-shadow: none;
      font-weight: 400;
      border: 0;
      outline: 0;
      letter-spacing: normal;
      color: white;
    }
    body {
      background: no-repeat center /cover;
      background-color: #edf0f5;
    }
  </style>
</head>

<body>
<div class="container" id="app">
  <div class="search-container">
    <div class="search-box">
      <input type="text" v-model="words" id="inp">
      <button>搜索一下</button>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script>
  const app = new Vue({
    el: '#app',
    data: {
      words: ''
    },
    mounted() {
      document.querySelector('#inp').focus()
    },
  })
</script>

</body>

</html>
相关推荐
发现一只大呆瓜11 分钟前
React-手把手带你实现 Keep-Alive 效果
前端·react.js·面试
酉鬼女又兒32 分钟前
入门前端CSS 媒体查询全解析:从入门到精通,打造完美响应式布局(可用于备赛蓝桥杯Web应用开发)
前端·css·职场和发展·蓝桥杯·前端框架·html5·媒体
Dxy123931021641 分钟前
HTML常用标签详解
前端·html
毛骗导演43 分钟前
@tencent-weixin/openclaw-weixin 插件深度解析(一):认证与会话管理机制
前端·架构
spencer_tseng1 小时前
Vue node_modules
javascript·vue.js
wefly20171 小时前
告别本地环境!m3u8live.cn一键实现 M3U8 链接预览与调试
前端·后端·python·音视频·m3u8·前端开发工具
SuperEugene1 小时前
前端 console 日志规范实战:高效调试 / 垃圾 log 清理与线上安全避坑|编码语法规范篇
开发语言·前端·javascript·vue.js·安全
发现一只大呆瓜1 小时前
Vue - @ 事件指南:原生 / 内置 / 自定义事件全解析
前端·vue.js·面试
庄小焱1 小时前
React——React基础语法(1)
前端·javascript·vue.js
pingan87872 小时前
试试 docx.js 一键生成 Word 文档,效果很不错
开发语言·前端·javascript·ecmascript·word