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>
相关推荐
Lkstar12 分钟前
Vue keep-alive 原理全解:LRU 缓存策略、源码级理解
前端·vue.js·面试
会联营的陆逊13 分钟前
html2canvas 1.4.1 在 iOS Safari 中生成图片卡住的问题排查与修复
前端
ZC跨境爬虫35 分钟前
跟着 MDN 学CSS day_13 :(深入理解CSS中的元素尺寸调整)
前端·javascript·css·ui·html·tensorflow
threelab1 小时前
Three.js 加载 3D Tiles 瓦片数据 | 三维可视化 / AI 提示词
开发语言·前端·javascript·人工智能·3d·着色器
百度地图开放平台1 小时前
我用百度地图 Skills 体系重构了物流调度系统,节省了 90% 的人力
前端·github
JavaAgent架构师1 小时前
前端AI工程化(九):AI Agent平台前端架构设计
前端·人工智能
_洋2 小时前
Three.js加载 .obj文件 和 .gltf文件
开发语言·javascript·ecmascript
梦想CAD控件2 小时前
网页端对DWG图纸进行预览与批注(CAD轻量化)
java·前端·javascript
代码煮茶2 小时前
Vue3 埋点实战 | 从 0 搭建前端用户行为埋点系统
vue.js
JustNow_Man2 小时前
【opencode】安装使用daytona沙箱插件
android·java·javascript