vue notes 7
16. Dynamic components
In addition to using conditional rendering (v-if/v-show), dynamic components can also be used to dynamically switch between different components somewhere in the page.
vue provides component tag to implement;
The attribute name of the is attribute on the component tag determines which component is used for rendering at the current location.
<component is="Box"></component> ==><Box></Box>
You can bind a variable in data to the is attribute and switch between different components by changing the value of the variable:
<component :is="mycomponent"></component>
<template> <div id="app"> <button @click="fn">xx</button> <components :is="com"></components> </div> </template> <script> import HelloWorld from './components/HelloWorld.vue' import HelloWorld2 from './components/HelloWorld2.vue' export default { name: 'app', data(){return{ flag:true, com:"HelloWorld", }}, components: { HelloWorld,"HelloWorld2" }, methods:{ fn(){ this.flag=!this.flag this.com=this.flag?"HelloWorld":"HelloWorld2" } } } </script>
17. Cache component
A new component object is created each time a dynamic component is switched.
The operation data of the previous component will not be saved after switching.
Use keep alive to cache dynamically switched components.
<keep-alive><component :is="Box"></component></keep-alive>
Two properties of keep alive:
- include determines which components can be cached
- exclude: other components are cached except the current component
- You can pass in a string or regular expression (when you pass in a regular expression, you need to add v-bind to the attribute to indicate that it is a JS syntax environment)
<keep-alive exclude="a,b"> <!-- except name by a perhaps b The other components are cached --> <component :is="view"></component> </keep-alive> <!-- To use regular expressions, use v-bind Cache name is a || b Components of--> <keep-alive :include="/a|b/"> <component :is="view"></component> </keep-alive>
Hook function of dynamic component:
Deactivated: only cached components exist. It is called when a component cached by keep alive is deactivated.
Activated: only cached components exist. It is called when a component cached by keep alive is activated.
<script> export default { data() { return { idcard: "", pwd:"" } }, methods:{ send(){ console.log(this.idcard,this.pwd) } }, mounted() { console.log("Only when first created") }, activated() { console.log("Page refresh is performed once every rendering") } } </script>
18. Asynchronous components
Load and cache components asynchronously:
1. Asynchronously loading components: components that cannot be used will not be loaded, so Web pages will be opened quickly. When you use this component, you will load it through asynchronous requests;
Official explanation: Vue allows you to define a component as a factory function that asynchronously parses (loads) the component definition, that is, Vue will only trigger the call of the factory function when it actually needs to render the component, and cache the results for rendering again in the future.
2. Component caching: components loaded asynchronously will be cached. When you reuse this component next time, there will be no delay, and the component will be loaded from the cache soon.
-
Method 1: load on demand through webpack 2.0
//1 Global: Vue.component('component-name',function(resolve){ //The require syntax tells webpack to automatically split the compiled code into different blocks //These blocks will be automatically downloaded through Ajax requests require(['./my-async-componnet'],resolve) }) //The global component name is registered, but there is only one name and no entity, which is equivalent to empty //When this component is needed, call the above factory function to trigger the asynchronous loading module method of webpack //Then asynchronously request a module. After the request is successful, the module content is the component entity part, rendered in the corresponding place, and the loaded content is also cached. //2 local new Vue({ components: { 'component-name':function(resolve) { require(['./my-component'], resolve) } } })
-
Method 2: return a promise (mainstream) through webpack2+es2015
//1 Global: Vue.component('component-name', ()=> import('./my-async-componnet')//This' import 'function will return a' Promise 'object ) //2 local: new Vue({ components: { 'component-name': () => import('./my-async-componnet')//This' import 'function will return a' Promise 'object. } })
-
Method 3: Advanced asynchronous component
//The factory object can return the following object, which contains some configuration parameters const AsyncComponent = () => ({ // Components to be loaded (this' import 'function will return a' Promise 'object.) component: import('./MyComponent.vue'), // Components used when asynchronous components are loaded loading: LoadingComponent, // Components to use when loading fails error: ErrorComponent, // Show the delay time of the component when loading. The default value is 200 (milliseconds) delay: 200, // If a timeout is provided and the component load times out, // The component used when the load failed is used. The default value is: ` Infinity` timeout: 3000 })
-
Example
<script> import Box from './Box.vue'; // import Box2 from './Box2.vue' // import Box3 from './Box3.vue' import LoadingComponent from "./LoadingComponent.vue" import ErrorComponent from "./ErrorComponent.vue" export default { components: { Box, Box2: (resolve) => { return require(["./Box2.vue"], resolve) }, Box3: () => import("./Box3.vue"), Box4: () => ({ // Component to be loaded (it should be a 'Promise' object) component: import('./Box4.vue'), // Components used when asynchronous components are loaded loading: LoadingComponent, // Components to use when loading fails error: ErrorComponent, // Show the delay time of the component when loading. The default value is 200 (milliseconds) delay: 200, // If a timeout is provided and the component load times out, // The component used when the load failed is used. The default value is: ` Infinity` timeout: 3000 }) } } </script>
19. Component summary
//Code used on template: Interpolation expression:{{}} Text instrumentation, label not recognized: v-text Text instrumentation, identification label: v-html Prevent the current tag from being recognized: v-pre instantiation Vue Removed on: v-clock Property binding: v-bind ===>Syntax sugar:":" Event binding instruction: v-on ===>Syntax sugar:"@" Event modifier : .stop=>Stop bubbling .once=>The event is unbound after being triggered once .capture =>Causes the event to be triggered during the capture phase .self=>The event is triggered when the element itself is the target object .native =>Add native events to subcomponents .passive =>Do not intercept default events Custom directives: v-xxx directive Conditional instruction: v-if/v-else v-show Cycle command: v-for Bidirectional binding instruction: v-model Attribute passing: attr Event delivery: listener Slot: New:v-slot used:slot //Code within the component data:()=>{} //data props:[],//Component properties comments:{},//Component mount directives:{},//Custom instruction filters:{},//filter watch:{},//monitor computed:{},//Calculation properties //Life cycle function beforeCreate(){},//vm cannot be operated before vm instantiation created(){},//vm instantiation completed beforeMount(){},//Before vm mounts to DOM mounted(){},//vm mount to DOM beforeUpdate(){},//Before data update updated(){}//Data update beforeDestroy(){}//Before vm destruction destroyed(){}//After vm destruction this What can I access? this.data;//Accessing data in data this.$emit(fu(),reg);//The function that triggers the binding of the parent component by reverse value transfer this.$root;//Access to root component this.$parent;//Access the parent component of the current component this.$children;//Access the sub components of the current component (the return value is an array) this.$destroy();//Destroy the current instance this.$refs;// The dom operation accesses the node with the ref attribute bound this.$nextTick(fn);//This function will be called after the component is mounted this.$on;//Binding event this.$off;//Event unbinding this.$bus;//Central event bus. After binding the new vm to the Vue prototype, all components can be accessed through this.$bus
20. Routing
1. Definition of route:
The route here does not refer to the hardware router we usually call. The route here is the path manager of SPA (single page application). Generally speaking, Vue router is the link path management system of WebApp.
vue's single page application is based on Routing and components. Routing is used to set access paths and map paths and components. The traditional page application uses some hyperlinks to realize page switching and jump. In vue router single page applications, it is the switching between paths, that is, the switching of components. The essence of routing module is to establish the mapping relationship between url and components.
The a tag cannot be used because Vue is a single page application (when your project is ready to be packaged and npm run build is run, the dist folder will be generated, which contains only static resources and an index.html page). Therefore, the tag you write does not work. You must use Vue router for management.
Back end Routing: for the front-end network request, different pathname s are used to perform different back-end services
Front end Routing: different web addresses correspond to their respective pages
Front end routing of vue: if SPA applications want to make routing effect, they have to judge the current website, and then switch components
vue router is dedicated to the function of switching components. It is a separate technology and depends on vue
Vue router is the official routing plug-in of vue.js. It is deeply integrated with vue.js and is suitable for building single page applications. Vue's single page application is based on Routing and components. Routing is used to set access paths and map paths and components.
2. Introduction of routing
-
cdn introduction:
-
Download the routing plug-in through node.js
//Install into project: npm i vue-router --save-dev//Note: This download is not good because it is easy to have problems after packaging npm i vue-router --save perhaps npm i vue-router --S //Import in the main.js entry file import Vue from "vue" import VueRouter from "vue-router"//Introducing routing tools import App from "./App.vue" Vue.use(VueRouter)//Injecting routing is to run routing related functions and bind things to vue, such as $router //Create routing tool const router=new VueRouter({ //routes routers generate switching components corresponding to many web addresses routes:[{path:"/home",component:()=>import("./home.vue")},//Specific routing path {path:"/about",component:()=>import("./about.vue")}] }) new Vue({ router,//Mount route to page render(h){return h(App)} }).$mount("#app") //Use to write < router View > < / router View > in App.vue //The component to which the route URL matches will be rendered on the label of the current component <template> <div id="app"> <router-view></router-view> </div> </template>
-
Create a vue environment with routes through vue scaffolding
//First, the scaffold must be installed globally //Create vue project vue create app //Select Manually select features //Check router in the space //Create project
3. Router view and router link labels
- Router view: the component matching the route URL will be rendered into the < router View > < / router View > tag of the current component.
- Router link: equivalent to a tag, which can jump to a route. (a tag can refresh the page, which is mainly used for external jump, and router link tag is mainly used for jump in the current station) < router link to = "/ XX" > < / router link >
4. The difference between this. $router and this.$route
Access the router through this.$route in any component, or access the current route through this.$route (used for routing parameters)
this.$router is equivalent to a global router object, which contains many properties and objects (such as history object). Any page can call its push(), replace(), go(), etc.
this.$route represents the current route object. Each route will have a route object, which is a local object. You can obtain the corresponding name, path, params, query and other attributes.
5. Declarative navigation router link routing parameters
< router link to = "/ XX" > < / router link >: indicates the link of the target route. When clicked, the internal will immediately transfer the value of to to router.push(), so this value can be a string or an object describing the target location.
<!-- character string to When the property is not an object, only the of the route can be matched path --> <router-link to="/home">Home</router-link> <!-- Render results --> <a href="home">Home</a> <!-- use v-bind of JS expression --> <router-link v-bind:to="'home'">Home</router-link> <!-- Don't write v-bind You can also, just like binding other properties --> <router-link :to="'home'">Home</router-link> <router-link :to="path">Home</router-link> <!-- ditto --> <router-link :to="{ path: 'home' }">Home</router-link> <router-link :to="{ name: 'user'}">User</router-link>
Parameter transfer
-
By writing directly after the route? id = form of value
<router-link to="/game?id=1">game</router-link> <router-link :to="'/game?id=' + id">game</router-link> // <router-link to="/xx?name=karen&pwd=123">go</router-link>
The corresponding route after rendering is: http://localhost:8090/#/my?id=1
In the corresponding my.vue component, you can access the passed parameters through this.$route.query
<template> <div>This is my page</div> </template> <script> export default { created() { console.log(this.$route.query); //Print {ID: '1'} } } </script>
-
Form of pass / back splice parameters
<router-link to="/my/9">My page</router-link> <router-link :to="'/my/' + id">My page</router-link>
The route after rendering is: http://localhost:8090/#/my/1 (now the value of id is 1)
In this way, you need to configure the route in route.js. After the path path '/ my', you need to splice: id to receive the value of route link id
{ path: '/my/:id', name: 'my', component: () => import('@/views/my.vue') }
In the my.vue component, you can access the id attribute through this.$route.params
<template> <div>This is my page</div> </template> <script> export default { console.log(this.$route.params); //Print {ID: '1'} } } </script>
3. Bind an object to the to attribute through v-bind, and indicate the path and parameters in the object through the path and query attributes
<router-link :to="{ path: '/my', query: { id: id } }">Click to go to my page</router-link>
The route rendered is: http://localhost:8090/#/my?id=1
The route configuration is: path: '/ my', do not match the parameters
In the my.vue component, you can access the id attribute through this.$route.query
<template> <div>This is my page</div> </template> <script> export default { name: '', components: {}, data() { return { } }, created() { console.log(this.$route.query); //Print {ID: '1'} } } </script>
4. Bind an object to the to attribute through v-bind, and indicate the path and parameters in the object through the name and params attributes - declarative navigation, named route - dynamic route parameter transmission
<router-link :to="{ name: 'my', params: { id: id } }">Click to go to my page</router-link>
The route rendered is: http://localhost:8090/#/my
The route configuration is: path: '/ my', no matching parameters are required, but the name attribute should be added to the route
const routes = [{ { path: "/my", name:"my", component: () => import("../my.vue") } ]
In the my.vue component, you can access the id attribute through this.$route.params
<template> <div>This is my page</div> </template> <script> export default { name: '', components: {}, data() { return { } }, created() { console.log(this.$route.params); //Print {ID: '1'} } } </script>
6. Program navigation parameters
Routing jump through JS code is called programmatic navigation
The basic form is: this.$router.push({path:"/xx",query:{name:"karen",pwd:123})
-
Basic parameter transfer method:
toMy() { // Layer 1 routing may not be added/ this.$router.push('/my'); // String. The path defined in the routing rule corresponds to the parameter in push this.$router.push('/my/' + this.id); // Splicing parameters The routing configuration is: path: '/my/:id' Render path: http://localhost:8080/dist/#/my/6 Take parameters params this.$router.push('/my?id=' + this.id); // Splicing parameters The routing configuration is: path: '/my' Render path: http://localhost:8080/dist/#/my?id=6 Take parameters query }
-
Object jump mode path and name
this.$router.push({ path: '/my' }) this.$router.push({ name: 'my' }) Render path: http://localhost:8080/#/my The routing configuration is: {path: '/my' , name: 'myow',component:()=>import('@/vires/my.vue')} this.$router.push({ path: '/my/' + this.id }); Render path: http://localhost:8080/#/my/9 The routing configuration is: {path: '/my/:id' , name: 'myow',component:()=>import('@/vires/my.vue')}
-
Pass parameter jump name and params (program navigation named route)
toMy() { this.$router.push({ name: 'my', params: { id: this.id } }); } //Render path: http://localhost:8090/#/my The routing configuration is: {path: '/my' , name: 'my',component:()=>import('@/views/my.vue')} stay my.vue Passed in this.$route.params Access to id Parameter value
-
Pass parameter jump path and query
toMy() { this.$router.push({ path: '/my', query: { id: this.id } }); } Render path: http://localhost:8090/#/my?id=1 The routing configuration is: {path: '/my' , name: 'my',component:()=>import('@/views/my.vue')} stay my.vue Passed in this.$route.query Access to id Parameter value
7. What is the difference between query and params parameters?
1,query Parameter transfer: matching path || matching name, params Parameter transfer: matching name params Special case of parameter transmission: when used / When splicing parameters, the matching is path,The corresponding page is params Take parameters 2,query Transmission parameters: url The parameters will be spliced behind the bar(?Parameter name 1=Parameter value 1&Parameter name 2=Parameter value 2), params Transmission parameters: url Parameters are not spliced behind the bar params Special case of parameter transmission: if the routing configuration is changed to/:variable url The column will splice parameters 3,query Parameter transfer: refresh page parameters will not be lost, params Pass parameters: refresh page parameters will be lost params Special case of parameter transmission: if the routing configuration is changed to/:If a variable receives a parameter, it will not be lost 4,query Pass parameter: Pass this.route.query Take parameters params Pass parameter: Pass this.route.params Take parameters
8. Route nesting
Redirect: redirect / / indicates that when you jump to this route, you will automatically go to a redirected route
When configuring nested routes, do not add "/" before the path// If "/" is added, it starts from the root path, that is, the path will be spliced after the port number. If "/" is not added, it starts from the current path
Path / * indicates that all paths are configured. It is generally used to set the route of 404 page. At the end, the routes are matched from top to bottom. After the matching is successful, the routes will no longer match.
Syntax:
/**The design of a routing object includes: path(Route matching path) component(Corresponding rendered components when matching paths) redirect(Re match another path when matching a path) children(Subroutines (by their array) name(The name of the route, which is convenient to match the route directly through the name): routes=[{path,component,redirect,children,name},{path,component,redirect,children,name}] **/ const routes = [{ path: '/', component: () => import("../views/root.vue"), redirect:"/goods_rank",// Re visit / goods by default when accessing /_ rank children: [{//Sub route name:"goods_rank", path: "goods_rank", component: () => import("../views/root/goods_rank.vue"), //goods_ The condition for loading the rank component is that the route matches: localhost:8080/goods_rank children: [{ name:"goods_rank_all", path: "goods_rank_all", component: () => import("../views/root/goods_rank/goods_rank_all.vue") //goods_ rank_ The condition for loading the all component is that the route matches: localhost:8080/goods_rank/goods_rank_all }, { path: "goods_rank_highpraise", name:"goods_rank_highpraise", component: () => import("../views/root/goods_rank/goods_rank_highpraise.vue") }, { path: "goods_rank_middlepraise", name:"goods_rank_middlepraise", component: () => import("../views/root/goods_rank/goods_rank_middlepraise.vue") }, { path: "goods_rank_badepraise", name:"goods_rank_badepraise", component: () => import("../views/root/goods_rank/goods_rank_badepraise.vue") }, { path: "*", component: () => import("../views/root/goods_rank/goods_rank_all.vue") } ] }, { path: "goods_inventory", name:"goods_inventory", component: () => import("../views/root/goods_inventory.vue") }, { path: "goods_new", name:"goods_new", component: () => import("../views/root/goods_new.vue") }, { path: "goods_set", name:"goods_set", component: () => import("../views/root/goods_set.vue") } ] }]
When jumping in a component:
//4 Syntax: //1 <router-link to="/The routing address of the component where the current code is located/To which sub route address">go</router-link> this.$router.push({path:"/The routing address of the component where the current code is located/To which sub route address"}) //2 <router-link to="To which sub route address">go</router-link> this.$router.push({path:"To which sub route address"}) //Note: the preceding / to be written represents the absolute route. If not written, it represents the route relative to the current route rather than the current parent component route //3 <router-link :to="{name:'Of registered routes name'}">go</router-link> this.$router.push({name:'Of registered routes name'}) example: <router-link to="/goods_rank/goods_rank_highpraise">go</router-link> this.$router.push({path:"/goods_rank/goods_rank_highpraise"}) <router-link :to="{name:'goods_rank_highpraise'}">go</router-link> this.$router.push({name:'goods_rank_highpraise'}) supplement: //replace is similar to push, but instead of adding a new record to history, it replaces the current history record this.$router.replace({path:"/home"}) this.$router.go(1)// A step forward in the browser record is equivalent to history.forward() this.$router.go(-1)// Step back to record, equivalent to history.back() this.$router.go(3)// Record 3 steps forward this.$router.go(-100)// If the history record is not enough, it will fail silently
9. Routing mode
**Hash mode: * * in the browser, the characters after the symbol "#", # and # are called hash, which can be read with window.location.hash;
Features: Although the hash is in the URL, it is not included in the HTTP request; It is used to guide the browser action. It is useless for the security of the server. The hash will not reload the page.
In the hash mode, only the contents before the hash symbol will be included in the request, such as http://www.xxx.com Therefore, for the back end, even if the route is not fully covered, no 404 error will be returned.
**History mode: * * history adopts the new features of HTML5; It also provides two new methods: pushState(), replaceState(), which can modify the browser history stack, and listening to state changes for popState events.
In the history mode, the URL of the front end must be consistent with the URL of the actual request to the back end, such as http://www.xxx.com/items/id . If the backend lacks routing processing for / items/id, it will return 404 error. Vue router's official website describes this way: "however, to play this mode well, you need background configuration support... Therefore, you need to add a candidate resource covering all situations on the server: if the URL does not match any static resources, you should return to the same index.html page, which is the page your app depends on.
const router=new VueRouter({ mode:"hash",//"history" routes:[{path:"/home",component:()=>import("./home.vue")}, {path:"/about",component:()=>import("./about.vue")}] })
Supplement: modifier of v-model
- v-model.trim: remove the space before and after
- v-model.lazy: change the underlying input event into a change event. Only when the cursor is out of focus and the content changes will the data of data change.
- v-model.number: when the input data is a pure number, convert the input data to a number type. (the default is String)