Components in Vue

This part will be divided into the following five sections:

  1. Use of components
  2. Parameter transfer between components
  3. Event passing between components
  4. slot
  5. Dynamic and asynchronous components

Preface: In single-page application development, there is only one HTML page in most cases, so the page jump of a single page is actually a switch between components, so this component actually acts as an independent HTML page, but this component can be reused, transfer values, and call at will. In a VUE, this is usually done with a vue-Router and a component, which is the component we’ll study next.

What is a component?

The component is a reusable Vue instance with a name that has the same options as New Vue, such as lifecycle hooks, data, computed, methods, etc. The only difference is that it does not have root instance options like EL.

There are two ways to register components

Global registration

Vue.component('my-component-name', {/ *... * /})
Copy the code

Local registration

var ComponentA = { / *... * / }

new Vue({
  el: '#app'.components: {
    'component-a': ComponentA
  }
})
Copy the code

Each component, whether global or local, needs a name. For example, my-component-name registered globally and Component-a registered locally are component names. The recommended way to name component names is to use hello-word, which is all lowercase letters and hyphens for different letters.

Usage scenarios for global registry components

    <div id="app">
      <btn-success></btn-success>
    </div>
    
    <script type="text/javascript">
      Vue.component('btn-success', {
        template: 
        
.methods: {onSuccessClick: function(){ alert('Hit the Success button'); }}});var vm = new Vue({ el: "#app",})
</script>
Copy the code

In the example above, we registered a global component called BTN-Success. We provided the component with a template, template, which is what the component will render, and added a click event, onSuccessClick, Clicking bTN-Success triggers the onSuccessClick method.

This is a separate module that maintains its own click events and lifecycle hooks. When we need to use it, we can display it in our EL using the

tag name. While developing with the VueCli build tool, Components will be split into separate files with a. Vue suffix, and each component will be independent of each other.

Note that the data option in the component no longer points to an object {}, but to a method called funvtion(){return {}}, which returns a separate object.

For example 🌰 we will just above the example transformed into a cumulative effect, click the button to add one at a time!

   <div id="app">
      <! Call the global component -->
      <btn-success></btn-success>
      <btn-success></btn-success>
      <btn-success></btn-success>
    </div>
    
    <script type="text/javascript">
      // Define the global component bTN-success
      Vue.component('btn-success', {
        template:  .data:function(){
          return {
            count: 0}},methods: {onSuccessClick: function(){
            this.count += 1}}});var vm = new Vue({
        el: "#app",})</script>
Copy the code

Note: At this point in the formation of the count value is currently available only in the components of the definition of the call, can’t call in the el, also need to be aware of is through the global registered components, whether or not a reference to it, it will always be included in the final build results, imagine when we are at pains to optimize tool configuration, hope to eventually build results as far as possible concise, Isn’t that a very desperate thing to do?

For this reason, VUE prefers to use a local registry for component definition.

Use scenarios for local registration components

Still based on the previous example, let’s modify the way to become a local registered component to complete the accumulation task!

   <div id="app">
      <! Call the global component -->
      <btn-success></btn-success>
      <btn-success></btn-success>
      <btn-success></btn-success>
    </div>
    
    <script type="text/javascript">
      var btnCountAdd = {
        template: {{count}}.data: function () {
                return {
                    count: 0}},methods: {
          onCountAddClick: function () {
            this.count += 1; }}};var vm = new Vue({
        el: "#app".components: {'btn-success': btnCountAdd
        }
      })
      
    </script>
Copy the code

The above code first declares a variable btnCountAdd and assigns it the template, data, and methods options. Then a bTN-Success component is registered in New Vue with the Components option pointing to btnCountAdd, which completes the partial registration of a component.

This doesn’t seem to be a good distinction from global registry components, because we don’t usually use this in real projects. We usually introduce components in a modular way, so let’s simulate the real world!

// Project structure├─ index.html ├─ btn-count-add.js ├─ main.jsCopy the code
// index.html

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

 <div id="app">
    <btn-count-add></btn-count-add> 
    <btn-count-add></btn-count-add> 
    <btn-count-add></btn-count-add> 
    <btn-count-add></btn-count-add> 
  </div>
// Import the module as ES6 module. Type must be set to module
<script src="./main.js" type="module"></script>
Copy the code
// main.js

import { btnCountAdd } from './btn-count-add.js'
var vm = new Vue({
    el: '#app'.components: {
        'btn-count-add': btnCountAdd
    }
});
Copy the code
// btn-count-add.js

 var btnCountAdd = {
    template: {{count}}.data: function () {
        return {
            count: 0}},methods: {
        onCountAddClick: function () {
            this.count += 1; }}};// ES6 export syntax, export it
export { btnCountAdd };
Copy the code

We abstracted btnCountAdd into the btn-count-add.js file and exported it using es6’s export syntax. This formed a separate module. When we needed to use btnCountAdd, You can import btnCountAdd by importing {btnCountAdd} from ‘./btn-count-add.js’ and register it in Vue with the components option.

This introduction is often used in a real project environment, especially when we use big tools such as Webpack and gulP.

When using a local registry to register components, although this approach makes modularization of the project easier and optimizes the packaged results, there is also a minor problem — every time you use a component, you need to reference it through an import.

This can be a hassle when there are too many components. Vue provides a more convenient way for automatic global registration. When building a project using Webpack+ vue-CLI, we can do this before new Vue in main.js:

// NPM import --save lodash
import upperFirst from 'lodash/upperFirst'
import camelCase from 'lodash/camelCase'

const requireComponent = require.context(
  // The relative path of its component directory
  './components'.// Whether to query the subdirectory
  false.// Match the regular expression of the underlying component filename to get the.vue ending file
  /.vue$/
)


requireComponent.keys().forEach(fileName= > {
  // Get the component configuration
  const componentConfig = requireComponent(fileName)

  // Get the PascalCase name of the component
  const componentName = upperFirst(
    camelCase(
      // Strip the './ 'at the beginning of the file name and the extension at the end
      fileName.replace(/^\.\/(.*)\.\w+$/.'$1')))// Globally register components
  Vue.component(
    componentName,
    // If the component option is exported via 'export default',
    // Then '.default 'is preferred,
    // Otherwise fall back to the root of the use module.
    componentConfig.default || componentConfig
  )
});
Copy the code

For example, btnsuccess. vue can be used directly with
, and unused components are not packaged into the build result.

Next: Passing parameters between components! Welcome to pay attention to, study together to discuss exchanges!

Thank you for reading, if you are helpful, welcome to pay attention to “CRMEB” nuggets. Code cloud has our open source mall project, knowledge payment project, JAVA version of the full open source mall system, study and study welcome to use, the old iron easily point a star bai, the boss reward fifty cents, points you twenty-five cents, 😂😂 pay attention to us to keep in touch!