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>
相关推荐
涔溪3 分钟前
深入了解 Vite 的核心特性 —— 开发服务器(Dev Server)和热更新(HMR)的底层工作机制
前端·vite
前端一课24 分钟前
【vue高频面试题】第 14 题:Vue3 中虚拟 DOM 是什么?为什么要用?如何提升性能?
前端·面试
前端一课25 分钟前
【vue高频面试题】第 17 题:Vue3 虚拟 DOM 与 PatchFlag 原理 + 静态节点提升
前端·面试
前端一课26 分钟前
【vue高频面试题】第 13 题:Vue 的 `nextTick` 原理是什么?为什么需要它?
前端·面试
前端一课26 分钟前
【vue高频面试题】第 12 题:Vue(尤其 Vue3)中父子组件通信方式有哪些?区别是什么?
前端·面试
前端一课29 分钟前
解释watch和computed的原理
前端·面试
前端一课31 分钟前
【vue高频面试题】第 18 题:Vue3 响应式原理中的 effect、依赖收集与依赖触发
前端·面试
前端一课31 分钟前
【vue高频面试题】第 19 题:Vue3 性能优化技巧
前端·面试
前端一课34 分钟前
【vue高频面试题】第 15 题:computed vs watch 区别 + 使用场景
前端·面试
前端一课34 分钟前
【vue高频面试题】第 20 题:Vue3 生命周期 + watch 执行顺序
前端·面试