【Vue3 从入门到实战 进阶式掌握完整知识体系】028-Vue中的高级语法:插件的定义和使用

5、插件的定义和使用

基本写法

<!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>hello vue</title>
  <!-- 引入Vue库 -->
  <script src="https://unpkg.com/vue@next"></script>
</head>

<body>
  <div id="root"></div>
</body>

<script>

  // plugnin 插件:也是把通用性的功能封装起来
  // 定义插件
  const myPlugin = {
    install(app, options){
      // 这个app就是根组件,通过app可以做很多事情
      console.log(app, options);
    }
  }

  const app = Vue.createApp({
    template: `
      <my-title />
    `
  });
  
  app.component("my-title", {
    template: `
      <div>hello world!</div>
    `
  });

  // 使用插件,此时可以传入参数
  app.use(myPlugin, { name: "zibo" });

  const vm = app.mount('#root');
</script>

</html>
复制代码

运行结果

image-20210614150600442.png

使用插件做更多事情

<!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>hello vue</title>
  <!-- 引入Vue库 -->
  <script src="https://unpkg.com/vue@next"></script>
</head>

<body>
  <div id="root"></div>
</body>

<script>

  // plugnin 插件:也是把通用性的功能封装起来
  // 定义插件
  const myPlugin = {
    install(app, options){
      // 这个app就是根组件,通过app可以做很多事情
      // 为后辈(子孙)组件添加属性
      app.provide('name', 'zibo');
      // 自定义指令
      app.directive('focus', {
        mounted(el){
          el.focus();
        }
      });
      // 扩展全局属性
      app.config.globalProperties.$sayHello = "hello zibo!";
    }
  }

  const app = Vue.createApp({
    template: `
      <my-title />
    `
  });
  
  app.component("my-title", {
    // 接收最顶层组件(祖上)传过来的属性
    inject: ['name'],
    mounted(){
      console.log(this.$sayHello);
    },
    // 接收之后,在模板里面可以直接使用
    template: `
    <div>
      <div>hello world!</div>
      <div>{{name}}</div>
      <input v-focus />
    </div>

    `
  });

  // 使用插件,此时可以传入参数
  app.use(myPlugin, { name: "zibo" });

  const vm = app.mount('#root');
</script>

</html>
复制代码

运行结果

image-20210614151916408.png

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享