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>
相关推荐
涛涛ing30 分钟前
我们开源了公司的内部组件库,然后被各业务线骂成了筛子
前端
赵_叶紫32 分钟前
1.Java AES-GCM 加解密入门:理解原理与字符串实战
前端
anyup36 分钟前
uView Pro X 2.0 发布:弃用 UTS,全面支持 TypeScript 的 uni-app x 蒸汽模式 UI 框架
前端·uni-app·ai编程
多加点辣也没关系39 分钟前
JavaScript|第42章:安全与最佳实践
开发语言·javascript·安全
泯泷44 分钟前
第三章:lit-html的威力 - 精通声明式模板
前端·javascript·web components
艾莉丝努力练剑1 小时前
【AI接入大模型SDK】解决接口连接异常问题
前端·c++·人工智能·学习·ai·架构
Nayana1 小时前
《Web 到 HarmonyOS》-- 布局与样式:CSS → Column / $r
前端
bai2732 小时前
npm 在 cmd 里能跑,Node 的 spawn 一调就 EINVAL:Windows 上 .cmd 的六种调法实测
javascript·后端
徐小夕2 小时前
折腾一年,我们正式发布 JitOffice:一款跑在浏览器里的 AI Office
前端·vue.js·github
恋猫de小郭2 小时前
Flutter A2UI 1.0 ,原来的 genui 也正式换成了这一套 SDK 了
android·前端·flutter