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>
相关推荐
JarvanMo16 分钟前
Fluwx 6.0 预览版本他来了
前端
KaMeidebaby19 分钟前
卡梅德生物技术快报|单 B 细胞抗体筛选服务:技术架构、流程实现与数据验证
前端·数据库·其他·百度·新浪微博
爱勇宝21 分钟前
别焦虑,也别躺平:给年轻程序员的一封信
前端·后端·架构
OpenTiny社区24 分钟前
2026 OpenTiny NEXT 产品调研启动!
前端·开源·github
德莱厄斯25 分钟前
GIS 开发要变天?看看高德空间智能给我们带来了什么!
前端·gis·agent
JarvanMo28 分钟前
Flutter.Dart的主构造函数(primary constructor)可能马上就要来了
前端
用户65868180338401 小时前
一个前端CLAUDE.md
前端
前端那点事1 小时前
彻底解决KeepAlive缓存乱象!Vue3精细化按需缓存+路径重置终极方案
前端·vue.js
前端那点事1 小时前
Vue 的 template 标签不能用 v-show?底层机制+踩坑复盘+生产级解决方案
前端·vue.js
前端那点事1 小时前
从零落地前端性能优化:全链路避坑+实战调优方案
前端·vue.js