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/[email protected]/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>
相关推荐
Yvette-W13 分钟前
【JavaScript】原型链 prototype 和 this 关键字的练习(老虎机)
开发语言·前端·javascript·ecmascript·原型模式
程序员JerrySUN21 分钟前
设计模式 Day 4:观察者模式(Observer Pattern)深度解析
javascript·观察者模式·设计模式
烂蜻蜓26 分钟前
HTML5 新元素:革新网页开发体验
前端·html·html5
阿丽塔~29 分钟前
Vue2/Vue3异同整理
vue.js
七月的尾巴←_←34 分钟前
Java8+Spring Boot + Vue + Langchain4j 实现阿里云百炼平台 AI 流式对话对接
vue.js·spring boot·阿里云
CsharpDev-奶豆哥1 小时前
使用JS+HTML+CSS编写提词器实例
javascript·css·html
在下千玦1 小时前
#关于require 与 import 相关了解
javascript·node.js
森叶1 小时前
利用本地 Express Web 服务解决复杂的 Electron 通信链路的问题
前端·electron·express
土豆丶杨1 小时前
vue3+electron 桌面应用初始化
javascript·vue.js·electron
冴羽2 小时前
SvelteKit 最新中文文档教程(18)—— 浅层路由和 Packaging
前端·javascript·svelte