Four ways to define global components

Four ways to define global components:

1. Use Vue.extend with Vue.component
2. Use the Vue.component method directly
3. Define the template string to In the script tag
4. Define the template string into the template tag

Before recognizing the four ways to define components, we first need to know what are components?

Components: It is used to split the code amount of Vue instances. It allows us to divide different functional modules into different components. What kind of functions we need in the future can just call the corresponding components.

  • Modularization: It is divided from the perspective of code logic; it facilitates layered development of code and ensures that each functional module has a single function.
  • Componentization: It is divided from the perspective of UI interface; componentization of the front end facilitates the reuse of UI components.

The first:

<script>
    //1、使用Vue.extend 配合Vue.component
    var login = Vue.extend({
    
    
      template: "<h1>登录</h1>",
    });
    // Vue.component('组件名',扩展名)
    Vue.component("loginto", login);
  </script>

The second type:

<script>
    //2、直接使用Vue.component方法:
    Vue.component("register", {
    
    
      template: "<h1>注册</h1>",
    });
  </script>

The third type:

 <!-- // 3、将模板字符串,定义到script标签中 -->
  <script id="tmpl" type="x-template">
    <div><a href="">登录</a>|<a href="">注册</a></div>
  </script>
  <!-- 同时,需要使用 Vue.component('组件名'{
    
    }) 来定义组件: -->
  <script>
    Vue.component("account", {
    
    
      template: "#tmpl",
    });
  </script>

The fourth type:

<!-- 视图层 -->
    <div id="app">
      <!-- 组件 -->
      <course></course>
    </div>
    <template id="course">
      <!-- 第四种方式 -->
      <div><a href="#">登录</a> | <a href="#">注册</a></div>
      <!-- <div><a href="#">登录</a> | <a href="#">注册</a></div> -->
    </template>
<!-- 4、将模板字符串,定义到template标签中-->
  <!-- 同时,需要使用 Vue.component 来定义组件: -->
  <script>
    Vue.component("course", {
    
    
      template: "#course",
    });
  </script>

Replenish:

Definition of private components:

Written in the Vue instantiation object, it is at the same level as data: {} and methods: {}.

 <!-- 视图层 -->
    <div id="app">
      <my-header></my-header>
    </div>
    <template id="mine">
      <div>
        我是第四种方式
      </div>
    </template>
<script>
    // 调度层 VM
    var vm = new Vue({
    
    
      // vue控制的区域
      el: "#app",
      data: {
    
    },
      methods: {
    
    },
      //私有定义 components
      components: {
    
    
        "my-header": {
    
    
          template: "#mine",
        },
      },
    });
  </script>

Guess you like

Origin blog.csdn.net/qq_58511059/article/details/128526045