vue里面创建全局或者局部自定义指令(directive)

93 阅读1分钟
<!DOCTYPE html>
<html lang="en">
  <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>Document</title>
    <script src="https://unpkg.com/vue@next"></script>
  </head>
  <body>
    <div id="root"></div>
  </body>
  <script>
    // 局部创建一个自定义指定directive
    // 这个自定义指令意思是挂载完成自动聚焦focus()
    const directive = {
      focus: {
        mounted(el) {
          el.focus();
        },
      },
    };
    const app = Vue.createApp({
      // 模板里面引用自定义指令
      // 局部自定义指令,需要先接收
      directives: directive,
      template: `
<input type='text' v-focus />
`,
    });
    // 创建全局hello自定义指令
    // app.directive("hello", {
    //   // hello 意思是挂载的时候,聚焦input框
    //   mounted(el) {
    //     el.focus();
    //   },
    // });
    const vm = app.mount("#root");
  </script>
</html>