1. What is componentization
Componentization is to extract the repeated code and combine it into components. The most important thing of components is reuse (reuse), which is located at the bottom of the framework. Other functions depend on components and can be used by different functions with strong independence.
Vue components are divided into global components and local components.
2. Global and local components
2.1 Differences between global and local Components
- Global components: Once a global component is registered, any Vue instance can use it.
- Local component: Can only be used in the Vue instance where it is currently under group test
2.2 Global Components
2.3 Partial Registration
Local registration effect picture:
2.4 Code Section
2.4.1 Global Component registration code
<! DOCTYPEhtml>
<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>Document</title>
</head>
<body>
<div id="app">
<! Step 2: Write component labels with dash syntax -->
<! You can register components with camel and dash nomenclature, but you must use dash nomenclature.
<content-header></content-header>
<template id="header">
<h2>I'm a template string</h2>
</template>
</div>
<script src=".. /lib/dep/plugins/vue.js"></script>
<script>
// Global component Step 1: Register global events
/** Global component registration syntax: Vue.component(' component name ', {data:" component data "// Unlike the instance, this data must be a function and must return an object template: the content or ID of the template // ES6 template syntax}) */
Vue.component("contentHeader", {
data() {
return{}},// Use the template string directly in template
// template: `
// <div>
// I am a template string
// </div>
/ / `
// Use the template tag on HTML to bind the template attribute in the component registry by ID
template: "#header"
})
let app = new Vue({
el: "#app".data() {
return{}}})</script>
</body>
</html>
Copy the code
2.4.2 Local component registration code
<! DOCTYPEhtml>
<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>Document</title>
</head>
<body>
<div id="app">
<index-search></index-search>
<! -- Local component 1 -->
<template id="demo2">
<h2>I'm Component two</h2>
</template>
<index-banner></index-banner>
</div>
<script src=".. /lib/dep/plugins/vue.js"></script>
<script>
// Local component
let demo3 = {
data() {
return {
text: "I am Component 3"}},template: `<div> {{text}} </div> `
}
let app = new Vue({
el: "#app".// Local components are registered in Vue instance components
components: {
// The format is component name: component content
Component 1 cannot be displayed because local components do not support template string writing
"index-search": '
I am component 1
."index-nav": "#demo2"."index-banner": demo3
}
})
</script>
</body>
</html>
Copy the code
3. Child and parent components
There is a hierarchy between components. One of the most important relationships is the parent-child relationship, where component B is registered in the components property of component A, so component A is the parent of component B, and component B can only be used in component A (scope).
Parent component passes value to child component
1. The parent component is bound to the child component label by v-bind
2. Sub-components receive data through props
Child components pass values to parent components
- In the child component, the event is emitted via $emit() and the parameters are passed.
- In the parent component, v-on is used to listen for child component events and receive parameters.
3.1 Parent Components pass values to child components
A child component cannot directly reference data from a parent component or Vue instance. It needs to be passed through the parent component and received by the child component through props.
In the component, use the option props to declare the data that needs to be received from the parent.
Props can be used in either of two ways: 1. An array of strings, the elements of which are the names of the data being passed.
<script>
Vue.component("index-header", {//props is recommended to use object form for more precision
// Format: props:[" parameters passed by the parent "]
props: ["index"."type"] // Method 1 is not recommended
})
</script>
Copy the code
2. Objects, objects can set the data type to be passed, can also set the default value and so on
<script>
Vue.component("index-header", {props:
// The object form is recommended
{
// Base type check (null matches all types)
propA:Number.// Pass parameter: pass type
// The type of the passed argument can be multiple
propB: [String.Number].// You can also define multiple attributes to be passed, such as parameter default values and whether an error is reported if no parameter is passed
propC: {type:Number.// Pass the type of the argument
// The default type of the argument displays 0 if no argument is passed
// However, if the parameter is a complex type, it should be written as a function and have a return value
// For example: default(){return []}
default:0 ,
required:false.// Whether an error is reported if the parent component does not pass arguments}}})</script>
Copy the code
3.2 Child Components pass values to parent components
Count =count (count=count); count=count (count=count); count (count=count)
4. Communication between components
Sometimes we need the parent to access the child directly, the child to access the parent directly, or the child to access the root.
Parent component accessing child component: use **children∗∗ or ∗children** or **children∗ or ∗∗refs**(recommended)
Child component access parent component: use **$parent**
$4.1 children
This.$children is an array type that contains all child component objects
Effect:
4.2 $refs
Refs use:
- The $refs and ref directives are usually used together.
- We set a special ID by binding the component label through ref.
- This.$refs.id is used to access this component.
Effect:
5. Modular
5.1 Overview of Modularity
1. Main problems of traditional development mode
Naming conflicts and file dependencies.
2. Use modularization to solve the preceding problems
Modularity is the encapsulation of a single function into a module (file), which is isolated from each other, but can also expose internal members through a specific interface, or can rely on other modules.
Modularity is a kind of idea, is the idea of splitting the big project into small modules. Modularity focuses on the encapsulation of functions, mainly for Javascript code, isolation and organization of duplicated Javascript code, and packaging it into modules with specific functions.
5.1 Closure implementation
Javascript modularity was originally implemented using closures. Modules are formed by enclosing variables with closures to block outside access.
var demo = (function () {
return {
add: (a, b) = > {
returna + b; }}}) ()Copy the code
5.2 Common. Js specification
The common.js specification states that within each module, the module variable represents the current module. This variable is an object whose exports property (module.exports) is the interface to the outside world. Loading a module loads the module.exports property of that module. The require method is used to load modules.
The CommonJS module has the following features:
1. All code runs in the module scope and does not pollute the global scope.
2. The module can be loaded multiple times, but it will only run once at the first time of loading, and then the result of running will be cached. After loading, the cache result will be read directly. For the module to run again, the cache must be cleared.
3. Modules are loaded in the order in which they appear in the code.
1.Modules are divided into single file modules and packages2.Module member exportmoduleExports andexports
3.Module member import:require("Module identifier")
var fs = require("fs")
module.exports = function getContent(path) {
return fs.readFileSync(path).toString()
}
Copy the code
5.3 ES6 Modularization
As defined in the specification for ES6 modularity
- Each JS file is an independent module
- Import module members using the import keyword
- Expose module members using the export keyword
Default import and default export
Default export and export syntax:
Note: Export Default can only be used once per module
//m1.jsDefault export syntax:export defaultMembers exported by default// Define private members
lat a= 0
let b= 0
function show(){
console.log("I am the method.")}// Expose the module private members for use by other module members
// Note: Each module can use export default only once
export default{
a,
b,
show
}
//index.jsDefault import syntax:importReceiving the namefrom 'Module Identifier'
import item from '.. /m1.js'
console.log(item.a)
console.log(item.B)
item.show()
Copy the code
Import on demand and export on demand
On-demand exports can be used multiple times per module
Import on demand and export on demand syntax:
//m1.js
// The on-demand export syntax exports the elements to be exported
export let name="How did the stock turn green?"
let age= 30
export age
export remove =() = >{console.log("Maotai fast Rising")}
//index.js
// On-demand import syntax: import {attribute name to import} from" module identifier"
import {name, age, remove} from "./m1.js"
console.log(name)
console.log(age)
Copy the code
6. The difference between modularity and componentization
modular
Modularity focuses on the encapsulation of functions or data. A set of related components can be defined as a module, an object that exposes a common validation method can be defined as a module, and a global JSON configuration file can be defined as a module. After encapsulation and isolation, it is more important to resolve dependencies between modules.
componentization
Componentization is more about the UI. You see a popup in the admin interface. The header, the content area, the confirmation button, and the footer can all be components.
** modules: ** Large modules are divided according to project business contents; ** Components: ** Abstracts components in terms of generality and reusability of small functions;