T1: vue.js component
The component registration
Global registration
Globally registered components can be used in any instance or component after registration and need to be registered before the root Vue instance is created.
Vue.component('exampleName', { /*option*/ });
Configuration when registering a component
The essence of a component is a reusable Vue instance whose configuration object is similar to new Vue().
There are two naming conventions for components: kebab-case and PascalCase, and only kebab-case is supported when HTML is used
template
Sets the structure of the component. HTML structure as a string.
There can only be one root element in the template
data
Used to store component data. A function that takes a data object as a return value.
The reason data is in function form: To ensure that the data called by each component instance is inside the closure of the function and does not affect each other.
Local registration
Components object under the instance configuration object
For local registration, the component name is used as the key name of the Components object, and must be quoted if kebab-case is used.
Declare the component object in advance and assign the value in the components object. You can also use the ES6 syntax with PascalCase nomenclature, such as Components: {MyComponentA, MyComponentB}.
Component communication
Parent component passes value to child component
Subcomponent: Sets the props option, a default array whose members are available as interpolations in the template. ⚠️ props do not have an attribute with the same name as data.
Props generally uses camelCase, without quotes in JS. The parent component is still bound using kebab-case.
Parent component: Sets corresponding properties in component element properties
- Static data:
dataName="theStringData"
- Dynamic data:
:dataName="attrOfFatherData"
Unidirectional data flow
Prop between parent and child components are bound in one-way downlink mode. Changes in data transmitted by the parent component affect the child component, and changes in data received by the child component do not affect the parent component, so the changes cannot be saved.
If prop is an object or array, the props of the child component will affect the props of the parent component.
Therefore, if the received PROPS data needs to be processed in a child component, it should be saved in data or computed as computed before processing.
Props Type detection
If you need to set the check type to filter the received values, write props as an object, the received values as key names, and the corresponding types as values. The value is null/undefined for any type and array for multiple types.
When the received value type is different from the expected value type, the value can still be received successfully, but with a warning.
props: {
parStr: String,
parNum: Number,
parArr: Array,
parObj: Object,
parAny: null,
parData: [Array, String, Boolean]
}
Copy the code
Props to verify
To validate a single prop in more detail, write the value of the prop member as an object:
parData: {
}
Copy the code
-
Type: The type of the value, as abbreviated
-
Required: Boolean value if required. If the value is true, it is mandatory. If no value is received, an error message is displayed.
-
Default: Used to set the default value for this prop. It takes effect if no value is received from the parent component. This should not be set at the same time as required.
If the default value is array or object, it must be in the form returned by the factory function. e.g.
Default: function () {retrun [1,2,3,4]}Copy the code
-
Validator: validator function. Warning is displayed if return is false
e.g.
validator (value) { return value.startsWith('abc')}Copy the code
[Note] The validation function does not get the instance through this, where this refers to the window
Non-props property value
The parent component sets properties to the child component that do not exist in props, so they are automatically bound to the root element of the child component.
If the child component root element already has a corresponding attribute, the parent component’s passed value overrides the original value. If you do not want to be overridden, add inheritAttrs: false to the child component configuration item. With the exception of style and class, the values of these two attributes will only be merged.
Child components pass values to parent components
The child passes the value to the parent through a custom event. The parent component listens for changes in the child component’s data
Emit () custom event and place it in the child component data change function so that the parent component listens for the emit() custom event and puts it in the child component data change function so that the parent component listens for the emit() custom event and puts it in the child component data change function so that the parent component listens for the emit() custom event to get the state of the child component. You can modify the data accordingly.
$emit uses the kebab-case name as well.
Custom event pass value #15
When the custom event function $emit() passes in the second argument, the parent component’s execution function gets the value when the event is emitted.
Components and v – model
Values are passed between non-parent-child components
Sibling component #18
Data transfer through the parent component
EventBus #19
EventBus is suitable for two components where the relationship is not clear
Completely unrelated components
Other means of communication
Usually used between components that are not directly related.
$root #20
$refs #21
Component slot
Component slots allow you to easily set component contents
Single slot #23
The <slot> tag is written into the template, and the contents of the component tag are inserted in place of the <slot> tag.
Note that ⚠】 component data is related to its rendering location. For example, component data can be obtained from component templates, while component content can only be obtained from instance data.
The content of <slot> is the default (fallback content) and takes effect when the component has no content.
Named slot #24
You need to set the name attribute for each slot. The unnamed slot is the default slot.
In component content. Template v-slot:slot-name> to write the contents of the slot. The template # slot – name >.
Scope slot #25
Used to make slots available to use data from child components
Slot prop: V-bind data that needs to be used by the slot to
, such as
default text
-
Multiple slots
<com-a> <template v-slot:slot-a="dataObj">{{ dataObj.value }}</template> <template v-slot:slot-b="dataObj">{{ dataObj.value }}</template> </com-a> Copy the code
-
Single default slot
<com-a v-slot="dataObj"> {{ dataObj.value }} {{ dataObj.index }} </com-a> Copy the code
The <template> element is omitted; V-slot is used directly for component elements; V-slot also omits the slot default name.
3. Often to deconstruct dataObj and assign it to:
<template #slot-a="{ value, index }">
{{ value }} {{ index }}
</template>
Copy the code
This is equivalent to {value, index} = dataObj
Built-in component
Dynamic Component #26
Fast switching of multiple components, such as tabs.
< Component :is=”MyComA”>
Dynamic component switching is accompanied by component instance uninstallation and creation, so component data is not retained
Keep alive – component # 27 ~ 28
The keep-alive component is used to preserve the state of the component or avoid re-rendering of the component in the case of data loss after the component switch described above.
Wrap < Component > with a <keep-alive> component element.
To specify which components will be cached, set the
include attribute to the name of the component to be cached. E.g. “ComA, ComB, ComC”/” “[‘ ComA ‘, ‘ComB’, ‘ComC’] / / Com [ABC] /”. The exclude attribute sets components that will not be cached.
The Max attribute specifies the maximum number of components in the cache
Transitional components
The transition component # 30
Used to animate elements and components in/out transitions:
- Conditional Rendering (using V-if)
- Conditional presentation (using V-show)
- Dynamic components
- Component root node
Wrap elements or components that need to be transitioned with a <transition> element. The transition effect is written in CSS, combined with the class name selection.
The Transition component comes with six classes to set the effects of the transition:
- Admission: V-enter, V-enter -to, V-enter -active
- Exit: V-leave, V-leave-to, V-leave-active
V-enter -to and V-leave are not commonly used. They are in the default state.
Change the transition class name from name- to name-.
Add the “Appear” attribute to make the element enter during the initial rendering.
Custom transition class name #32
In addition to the transition component’s native class name, you can customize the class name to control the transition through the following HTML attributes:
- Set the attributes of the entry class name: enter-class, enter-to-class, and enter-active-class
- Set the attributes of the exit class name: leave-class, leave-to-class, leave-active-class
- Set the attributes of the initial render class name: appear-class, Appear -to-class, Appear -active-class
It is usually used in conjunction with third-party CSS animation libraries, such as animation.css
The transition – group component # 33
The v-move class name is used to set the effect of an element shift caused by a list element change. Exit elements will be off scale during exit, which does not affect subsequent elements.
T2: Vue Router
Vue Router is an official plug-in for vue.js for fast single-page applications.
Single page application #2
The main functions of SPA (Single Page Application) websites are concentrated in a Single Page, which is common in background management systems, mobile terminals and small programs
Advantages: The development of front and back end is separated, which improves the development efficiency; When the service scenario is switched, the structure is partially updated. Good user experience, closer to native application
Cons: Bad for SEO; The first screen loading speed is slow; The page complexity is high
Native front-end routing
Mapping between URLS and content. Front-end routing can be implemented in two ways:
Hash #4~5
Hash is in the URL
Determine different hash values to request different module pages
encapsulation
var router = {
routes: {}, // Route store location: store the mapping between url and content handler functionThe route:function (path, callback) {
this.routes[path] = callback;
},
init: function () {
var that = this;
window.onhashchange = function () {
var hash = location.hash.replace(The '#'.' '); that.routes[hash] && that.routes[hash](); }}};Copy the code
Features of hash mode:
Good compatibility; Address contains #, not beautiful; Forward and backward cumbersome.
History #6~7
History is provided by HTML5
The popState event listens for forward and backward operations and detects state
History features: easy to implement, beautiful address; A complete advance or retreat; More data can be stored; Not compatible with older browsers; This path is requested during refreshing and requires the cooperation of the back end.
Basic use of Vue Router
Can use CDN, NPM package, JS file import
- Configure Vue routing components
and
on View side (HTML)
- Define the components used in routing
- Set the routing rule routes to match the address and component
- Create a Vue Router instance and configure routes under the Routes property with the preceding value
- Inject the route under the Router property in the Vue instance
At this point, the Vue instance will have new members: Router and Router and Router and Route. Router is an instance of a Vue route that invokes routing methods. Router is an instance of a Vue route that invokes routing methods. Router is an instance of a Vue route that invokes routing methods. Route is a routing rule.
The name of multiple views
Requirement: After routing the navigation, you want to display multiple components (views) at the same level, that is, multiple views for one URL
Handling: Naming views
-
Add <router-view> and set the name attribute (unset default name)
-
Components of routes, for example:
// Note that component and components are two items components: { viewNameA: componentNameA, default: componentNameB } Copy the code
Dynamic routing
Requirement: Multiple urls of the same class correspond to a component, and component content varies depending on some parameters of the URL
Processing:
- Set in the path of the routes ruleThe path parameter, um participant.
path: 'user/:id'
, id is the path parameter, to:
At the beginning, it’s stored invm.$route.params
中 - Use path parameters in the component template of such urls to produce different component content
In dynamic routing, components are reused, but their contents are modified instead of being destroyed or regenerated, so component hooks are not used.
Listen for route parameter #12
Requirement: Responds to route parameter changes
Handling: Listen for $route through the component’s watch TAB
e.g.
watch: {
$route (route) {
}
}
Copy the code
Route parameters #13 to 14 are transmitted
Requirement: When a dynamically routed component needs to be used in multiple places, you should not call vm.$route.params directly from the component to avoid coupling
Processing: The parameter is transmitted through a route
- Added to the routing rule
props: true
. The path parameter must be received by the props of the component, notvm.$route.params
- Component configuration props, for example:
props: [id]
- The component template interpolates path parameters directly
Multiple named views
If there are multiple named views (see []), the props item under the routing rule in Step 1 should be rewritten as an object, and each view enables or disables the props. Props: {default: true, viewNameA: true}
Pass static parameters
Example: Props: {default: true, sidebar: {a:1, b:2}}
Nested routines by #15
Nested sub-routes under the routing item
- Add
and
to the component template to form a nesting of views.
- The children item is set in the route, and the value is equivalent to the structure of routes. The route nesting is formed according to the view nesting structure.
Programmatic navigation
Set up navigation through functions
Navigation is achieved by invoking the route instance method: vm.$router.push()
The argument can be a URL string or an object {path: ‘/user’}
After routing
For long urls, add the name attribute to the routing rule object to simplify navigation configuration, save the NEED to write urls, and make path parameters clearer.
e.g.
routes = [{ path: '/user/:id/info/school', name: 'school', component: School }]
<router-link :to="{ name: 'school', params: {id: 1} }"></router-link>
The alias # 19
The alias property, whose value is a URL string, usually consists of critical path variables
This way, it can be accessed in the address bar or in <router-link> with an alias address
Difference with name access:
In the case of name access, the address bar is the original URL, and in the case of alias access, the address bar is the alias path.
Redirect # 18
Redirects common error paths to existing pages
E.g. redirect: ‘/’ to the home page
Navigation guard #20
Monitor each route and perform some custom processing operations
router.beforeEach(function (to, from, next) {
// to: destination address; From the address of the source; Next: Indicates the next operation
// next() releases no arguments
// next(false) blocks this route
// next('/user') takes the URL to block the original route and navigate to the new address
// Next should have one and only one time, can be combined with the conditions to judge
});
Copy the code
VueRouter’s History mode #21
The above routes are based on the Default Hash mode of the VueRouter
If you want to use History mode, configure mode ‘History’ in the router instance.
T3: Vue CLI
LIVE:
Developers need to have the following abilities:
- Programming ability (hard power)
- Communication skills (Soft power)
Technical problems of the way of communication, to improve the efficiency of communication:
- Complete information is attached and key codes are displayed. The description is clear and well-resourced.
- Questions should be accurate and focused
- Don’t ask easy questions
Knowledge questions:
- First offer your own ideas and guide the other person to think
- Scene: the repetition
- Make good use of the document
Problems encountered:
- First look at the console error
- x
- x
- Intercepting error information
- In the code
- Propose personal thinking (sublimation)
Web Components
W3C Component Specification
The framework serves large projects; small projects use plug-ins.
Technology is for the business, technology to meet the needs.
Custom elements
Customize elements in JS code and introduce HTML
- Declare a class for a custom element, which can be inherited from HTMLElement or a concrete element’s class.
- Use Windows. CustomElements. Define ()
shadow DOM
Attaching the Shadow Tree to the main DOM tree facilitates the closure of various HTML sections.
In shadow Tree, you can also call the document method.