This is the 22nd day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

Vue componentization

Component-oriented programming

Divide a page into N modules

Note: The demo environment is Vue scaffolding for the demonstration of the project

Creating a local component

Syntax format:

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

Example:

Register a component named my-component-name

Component content

First local component

<template> <div class="home"> <img alt="Vue logo" src=".. /assets/logo.png"> <HelloWorld msg="Welcome to Your Vue.js App"/> <! <my-component-name/> </div> </template> <script> // import Vue from 'Vue' // @is an alias to/SRC Import the HelloWorld from '@ / components/HelloWorld. Vue' create local components / / Vue.com ponent (' my - component - name, {template: '<h3> first component </h3>'}) export default {name: 'Home', components: {HelloWorld}} </script>Copy the code

Creating a global component

  • Create a new component vue file (shown in this section as modifying the original component)

The basic structure of a component

<template> <div class="hello"> <h1> First global component </h1> </div> </template> 'HelloWorld', } </script> <! -- Add "scoped" attribute to limit CSS to this component only --> <style scoped lang="less"> h3 { margin: 40px 0 0; } ul { list-style-type: none; padding: 0; } li { display: inline-block; margin: 0 10px; } a { color: #42b983; } </style>Copy the code
  • Import the component

    import HelloWorld from '@/components/HelloWorld.vue'

    @ indicates the SRC directory

  • Register the component

 export default {
   name: 'Home',
   components: {
     HelloWorld
   }
 }
Copy the code
  • Using this component

To reuse

Just use the label

<template> <div class="home"> <img alt="Vue logo" src=".. /assets/logo.png"> <HelloWorld/> <HelloWorld/> <HelloWorld/> <! <my-component-name/> </div> </template> <script> // import Vue from 'Vue' // @is an alias to/SRC Import the HelloWorld from '@ / components/HelloWorld. Vue' create local components / / Vue.com ponent (' my - component - name, {template: '<h3> first component </h3>'}) export default {name: 'Home', components: {HelloWorld}} </script>Copy the code

Effect:

Matters needing attention:

Data must be a function

<template> <div class="hello"> <h1> First global component </h1> <ul> <li>{{name}}</li> </ul> </div> </template> <script> export Default {name: 'HelloWorld', data() {return {'name': 'component'}}} </script> <! -- Add "scoped" attribute to limit CSS to this component only --> <style scoped lang="less"> h3 { margin: 40px 0 0; } ul { list-style-type: none; padding: 0; } li { display: inline-block; margin: 0 10px; } a { color: #42b983; } </style>Copy the code

Operation effect:

Creating a component can be interpreted as customizing it with an HTML tag

The purpose of splitting components is reuse