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>
相关推荐
Drift_Dream4 分钟前
虚拟滚动:优化长列表性能的利器
前端
逃离疯人院4 分钟前
前端性能深度解析:网络响应时间与实际渲染时间的鸿沟
前端
国服第二切图仔10 分钟前
Electron for鸿蒙PC项目实战之天气预报应用
javascript·electron·harmonyos·鸿蒙pc
VX:Fegn089514 分钟前
计算机毕业设计|基于springboot + vue酒店预约系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
我是若尘14 分钟前
🚀 深入理解 Claude Code:从入门到精通的能力全景图
前端
老前端的功夫22 分钟前
Webpack 深度解析:从配置哲学到编译原理
前端·webpack·前端框架·node.js
重铸码农荣光26 分钟前
🌟 Vibe Coding 时代:用自然语言打造你的专属 AI 单词应用
前端·vibecoding
MegatronKing27 分钟前
SSL密钥协商导致抓包失败的原因分析
前端·https·测试
Kratzdisteln30 分钟前
【TIDE DIARY 5】cursor; web; api-key; log
前端
Danny_FD30 分钟前
使用docx库实现文档导出
前端·javascript