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>
相关推荐
用户713874229001 分钟前
PKCE 的 S256 算法深度剖析:从协议设计到密码学原理
前端
闪闪发光得欧2 分钟前
StreamTokenizer的源码分析和使用方法详细分析
前端
李剑一3 分钟前
华为一面就问网络安全?面试官:请简述一下 XSS/CSRF 的攻击面与前端侧的防护
前端·面试
TrisighT5 分钟前
uni-app鸿蒙原生应用开发实战(下):核心功能实现与技术细节
vue.js·harmonyos
竹林8186 分钟前
被合约事件搞到失眠?我踩了三天坑,终于写出一份监听智能合约事件的实战指南
前端·javascript
用户059540174468 分钟前
把 AI 记忆验证从手工 Log 换成 Pytest+Mem0,上下文丢失 bug 减少 90%
前端·css
在逃花果山的小松9 分钟前
容器化部署实战:从Dockerfile到Kubernetes上云
javascript
艾利克斯冰21 分钟前
TypeScript 静态类型入门教程:可选静态类型与类型推导详
前端·javascript·typescript
GuWenyue25 分钟前
告别命名混乱!5步掌握BEM规范,写出易维护的前端页面
前端·javascript·面试
小林ixn26 分钟前
BEM 命名规范与 CSS 重置:打造优雅的按钮页面实战
前端·css