vue组件和slot插槽

vue组件

什么是组件: 组件的出现,就是为了拆分Vue实例的代码量的,能够让我们以不同的组件,来划分不同的功能模块,将来我们需要什么样的功能,就可以去调用对应的组件即可。

组件化和模块化的不同:

  1. 模块化:是从代码逻辑的角度进行划分的;方便代码分层开发,保证每个功能模块的职能单一(高内聚,低耦合)
  2. 组件化:是从UI界面的角度进行划分的;前端的组件化,方便UI组件的重用

将模板字符串,定义到template标签中,同时,需要使用 Vue.component 来定义组件

<body>
    <div id="app">
      <login></login>
      <outin></outin>
    </div>
    <template id="login">
      <div><a href="#">登录</a> | <a href="#">注册</a></div>
    </template>
    <template id="outin">
      <div><a href="">退出</a></div>
    </template>
    <script>
      Vue.component("login", {
        template: "#login",
      });

      const vm = new Vue({
        el: "#app",
        data: {},
        methods: {},
        components: {
          outin: {
            template: "#outin",
          },
        },
      });
    </script>
  </body>

 在组件中,data需要被定义为一个方法,例如

Vue.component("login", {
        template: "#login",
        data() {
          return {
            flag: true,
            Num: 0,
          };
        },
        methods: {
          add(n) {
            this.Num += n;
          },
        },
        beforeCreate() {
          console.log(1);
        },
        created() {
          console.log(2);
        },
        beforeDestroy() {
          console.log(3);
        },
        destroyed() {
          console.log(4);
        },
      });

 插槽的使用

在子组件中放一个占位符

<course type="free" size="10">
<template v-slot:header>免费</template>
<template v-slot:footer>底部</template></course>
      <course type="boutique">精品</course>
      <course type="discount">折扣</course>

<h2><slot name="header"></slot>课程</h2>

猜你喜欢

转载自blog.csdn.net/m0_63349753/article/details/126999213