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>
相关推荐
不懂的浪漫1 分钟前
AI 时代还需要买课吗?我用 Skills + Markdown + HTML 搭了一套自学系统
前端·人工智能·html·skill
前端的阶梯4 分钟前
Conda 开发 Python 程序完全指南
前端·人工智能·后端
zhengfei6116 分钟前
第2章 Agent 核心组件深度解析
前端·javascript·react.js
Linsk11 分钟前
前端代码压缩对浏览器兼容性的影响
前端
yingyima15 分钟前
凌晨3点的闹钟:分布式定时任务设计实战
前端
用户814238611884117 分钟前
iOS ObjectC棕地应用集成Expo(React Native)的过程及踩坑
前端
GuWen_yue18 分钟前
LeetCode 76 最小覆盖子串|JS 滑动窗口标准解法(逐行精讲)
javascript·算法·leetcode
lichenyang45321 分钟前
HMRouter 完整能力清单:从初始化到拦截器/对话框/生命周期/转场动画一站式查阅
前端
lichenyang45331 分钟前
鸿蒙电商 Demo v2:真实商品接口 + 支付/订单闭环 + 收藏功能,外加一个 ArkUI V2 @Builder 响应式断链的硬核坑
前端·后端
前端的阶梯32 分钟前
如何节省你的token,请看CodeGraph
前端·人工智能·后端