1. 程式人生 > 其它 >vue之自定義指令(文字框獲得焦點)

vue之自定義指令(文字框獲得焦點)

app.vue

<template>
  <div>
    <h1>App 根元件</h1>

    <hr />

    <!-- 使用元件 -->
    <my-home></my-home>
  </div>
</template>

<script>
// 匯入元件
import MyHome from './Home.vue'

export default {
  name: 'MyApp',
  // 註冊元件
  components: {
    MyHome,
  },
}
</script> <style lang="less" scoped></style>
Home.vue
<template>
  <div class="home-container">
    <h3 v-color="'red'">MyHome 元件 --- {{ count }}</h3>
    <hr />

    <input type="text" class="form-control" v-focus v-color="'cyan'" />
    <button 
type="button" class="btn btn-primary" @click="count += 1">+1</button> </div> </template> <script> export default { name: 'MyHome', data() { return { count: 0, } }, directives: { // focus: { // mounted(el) { // el.focus() // }, // }, }, }
</script> <style lang="less" scoped> .home-container { border: 1px solid #efefef; box-shadow: 0px 1px 10px #efefef; border-radius: 4px; padding: 20px; margin: 20px; } input.form-control { width: 280px; } </style>

 main.js(自定義全域性指令)

// 宣告全域性自定義指令
app.directive('focus', {
  mounted(el) {
    console.log('mounted')
    el.focus()
  },
  updated(el) {
    console.log('updated')
    el.focus()
  },
})