Catalogue of Series Articles
Last time we talked about some instructions like v-model and so on, this time we talked about components
1. Components
Duplicate page structure, data, logic can all be extracted into one component
- Simple, efficient and no repetition
- Similarity between components and instances: data/methods/computed/watch, etc.
Be careful: - The difference between data and Vue instances is
- The data in the component is a function and needs to return an object
- Component has no el option
- A template represents its page structure (with and only with one root element)
Each component is an independent running scope, data, logic without any association
1.1, Global Components
Global and local: different ways of registration have different application scopes
Note: Note the naming conventions
Path: Implement a global component
- Define a global component
- Write Component Options
- Using Components
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div id="app" v-cloak> <content-a></content-a> </div> <script src="./vue.js"></script> <script> Vue.component( "content-a", { template: ` <div> <button @click="add">plus</button> <span>{{count}}</span> <button @click="cut">reduce</button> </div> `, data(){ return{ count: 1 } }, methods: { add(){ this.count++ }, cut(){ this.count-- } } } ) let vm = new Vue({ el: '#app', data: { msg:'ok,ok', }, component:{ }, methods: { fn(e) { //msg = latest value this.msg = e.target.value } }, filters:{ filter01:function (vl) { return vl+'filter01' }, filter02:function (vl) { return vl+'filter02' }, capita : function (value) { return value.charAt(0).toUpperCase() + value.slice(1) } }, directives: { "focus": { inserted(dom) { dom.focus(); } } } }) </script> </body> </html>
This code adds to or subtracts from count and is also an example of a global filter
1.2, Local Components
Implementation of Local Components
- Define local component names in instance option compoents
- Define options (template, data(),...) in objects corresponding to component names
- Using components in the instance view
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div id="app" v-cloak> <content-a></content-a> <content-b></content-b> </div> <script src="./vue.js"></script> <script> Vue.component( "content-a", { template: ` <div> <button @click="add">plus</button> <span>{{count}}</span> <button @click="cut">reduce</button> </div> `, data(){ return{ count: 1 } }, methods: { add(){ this.count++ }, cut(){ this.count-- } } } ) let vm = new Vue({ el: '#app', data: { msg:'ok,ok', }, components:{ 'content-b':{ template: ` <div> <button @click="add">plus</button> <span>{{count}}</span> <button @click="cut">reduce</button> </div> `, data(){ return{ count: 1 } }, methods: { add(){ this.count++ }, cut(){ this.count-- } } } }, methods: { fn(e) { //msg = latest value this.msg = e.target.value } }, filters:{ filter01:function (vl) { return vl+'filter01' }, filter02:function (vl) { return vl+'filter02' }, capita : function (value) { return value.charAt(0).toUpperCase() + value.slice(1) } }, directives: { "focus": { inserted(dom) { dom.focus(); } } } }) </script> </body> </html>
1.3. Nesting of components
- Global Components Nested Global Components
- Local components nest global components
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div id="app" v-cloak> <content-c></content-c> </div> <script src="./vue.js"></script> <script> Vue.component( "content-a", { template: ` <div> <button @click="add">plus</button> <span>{{count}}</span> <button @click="cut">reduce</button> </div> `, data(){ return{ count: 1 } }, methods: { add(){ this.count++ }, cut(){ this.count-- } } } ) let vm = new Vue({ el: '#app', data: { msg:'ok,ok', }, components:{ 'content-b':{ template: ` <div> <button @click="add">plus</button> <span>{{count}}</span> <button @click="cut">reduce</button> </div> `, data(){ return{ count: 1 } }, methods: { add(){ this.count++ }, cut(){ this.count-- } } }, 'content-c':{ template: ` <content-a></content-a> `, data(){ return{ count: 1 } }, methods: { add(){ this.count++ }, cut(){ this.count-- } } } }, methods: { fn(e) { //msg = latest value this.msg = e.target.value } }, filters:{ filter01:function (vl) { return vl+'filter01' }, filter02:function (vl) { return vl+'filter02' }, capita : function (value) { return value.charAt(0).toUpperCase() + value.slice(1) } }, directives: { "focus": { inserted(dom) { dom.focus(); } } } }) </script> </body> </html>
1.4. Communication between components
Component Nesting=>Parent and Child Components=>Parent Components Pass Data to Child Components Use=>Pass Value Between Components=>Also known as communication between components
Communication between components can be divided into:
- Parent-Child Component Communication
Parent to Child Components
Child to parent components - Brother Component Communication
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div id="app"> <!-- Subcomponents --> <child-a :msg="msgP"></child-a> </div> <script src="./vue.js"></script> <script> Vue.component('child-a', { template: ` <div> I am a child component{{count}} {{msg}} </div> `, data() { return { count: 100 } }, props: ['msg'] }) let vm = new Vue({ el: '#app', data: { msgP: 'I am the parent component' } }) </script> </body> </html>
2. Routing
Differences between components and modules
- Module: Focus on encapsulation of functionality or data
- Component: Contains template s, style s, and scripts, and its script can be composed of various modules
Single Page Application (SPA for short)
- Traditional mode requires that each page and its content be requested from the server once and again. If the network is poor, the experience will feel slow.
- SPA mode, the first load will request all resources to switch between page modules and will not request the server again
SPA Advantages:
- User experience is good because front-end operations barely feel network latency
- Fully componentized development, where there is only one page, the work that originally belonged to one page is categorized as one component
SPA Disadvantages:
- The first screen loads slowly (you can only load what you need)
- Adverse to SEO (server-side rendering can solve)
- High development difficulty (framework)
Single Page Application SPA-Implementation Principle
- spa can be achieved by anchoring links to page addresses
- Hash (anchor link) after link address #
- A change in hash value does not trigger a page refresh
- The hash value is part of the url address and is stored on the page address where we can get it
- hash can be monitored through events and is worth changing
- Having a hash value allows you to switch between different content based on different hash values
2.1. Implementation of js-based routing
From the previous section, you can see that front-end routing can be switched using the hash value change feature
- Implement navigation structure ('#/aaa')
- onhashchange events listen for changes in hash values
- Get hash value to change view content depending on value
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <ul> <li><a href="#/aaa">aaa</a></li> <li><a href="#/bbb">bbb</a></li> <li><a href="#/ccc">ccc</a></li> <li><a href="#/ddd">ddd</a></li> </ul> <!-- container --> <div id="main"></div> <script> // Render different identities based on different content let oBox = document.getElementById('main') window.onhashchange = function () { // Get hash value let hash = location.hash console.log(hash) hash = hash.replace('#/', '') switch (hash) { case "aaa": oBox.innerText = 'AAA' break case "bbb": oBox.innerText = 'BBB' break case "ccc": oBox.innerText = 'CCC' break case "ddd": oBox.innerText = 'DDD' break default: break } } </script> </body> </html>
2.2, vue-router implementation
- Vue-Router is the official route manager for Vue.js.
- It is deeply integrated with the core of Vue.js, making it easy to build single-page applications
- Implements displaying different content based on different request addresses
- To develop a project using vue, front-end routing must be implemented using vue-router
A js file needs to be introduced:
- Can npm
- cdn
- You can also download imports directly
Basic grammar:
- Import Vue and vue-router
- Setting up content in HTML
- Instantiate routing objects, configure routing rules
- Create components corresponding to routes
- Mount the router instance onto the vue instance
2.Set up HTML Content in <!-- router-link Will be rendered eventually a Label, to Specify the jump address for the route --> <router-link to="/users">user management</router-link> <router-link to="/home">First page display</router-link> <!-- The components to which the route matches will be rendered here --> <router-view></router-view>
// 3. Configure Routing Rules var router = new VueRouter({ routes: [ { path: '/users', component: Users } { path: '/home', component: Home } ] });
// 4. Create Components let Home = { template: '<div>This is Home content</div>' }; let Users = { template: '<div>This is user managed content</div>' };
// 5. Mount the router instance onto the vue instance var vm = new Vue({ el: '#app', router });
2.3. Code implementation vue-router
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div id="app"> <!-- Configuration Path --> <router-link to="/home">homepage</router-link> <router-link to="/top">Hotspot</router-link> <router-link to="/abouts">About us</router-link> <!-- Displayed Content --> <router-view></router-view> </div> <script src="./vue.js"></script> <script src="./vue-router.js"></script> <script> // Template Content let Home = { template: `<div><span>homepage</span></div>` } let Top = { template: `<div><span>Hotspot</span></div>` } let Abouts = { template: `<div><span>About us</span></div>` } // Matching rules let router = new VueRouter({ routes: [{ path: '/home', component: Home }, { path: '/top', component: Top }, { path: '/abouts', component: Abouts }] }) let vm = new Vue({ el: '#app', data: {}, router }) </script> </body> </html>
2.4. Implementing dynamic routing
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="./vue.js"></script> <script src="./vue-router.js"></script> </head> <body> <div id="dianshi"> <router-link to="/item/8">What to see This is my millet TV</router-link> <router-link to="/item/9">What do you think this is my Huawei TV?</router-link> <router-view></router-view> </div> <script> let home = { template: `<div>I am home{{$route.params.id}}</div>`, } let router = new VueRouter({ routes: [{ path: '/item/:id', component: home }] }) let vue = new Vue({ el: '#dianshi', data: { msg: 'hello' }, router }) </script> </body> </html>
2.5, to attribute
to has many ways of assigning values
<!-- General Jump --> <!-- <router-link to="/aaa">aaa</router-link> --> <!-- variable --> <!-- <router-link :to="bbb">bbb</router-link> --> <!-- According to Object name Jump --> (Be careful:name Value is a string) <!-- <router-link :to="{name:'ccc'}">ccc</router-link> --> <!-- According to Object path Jump -->(Note: Must be added/ Otherwise it is easy to get confused) <!-- <router-link :to="{path:'/ddd'}">ddd</router-link> --> <!-- Jump with parameters --> (Note getting parameters route Do not write as router) <!--<router-link :to="{name:'eee',params:{id:1}}">Sports</router-link> --> <router-view></router-view>
Code implementation:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div id="app"> <!-- Configuration Path --> <router-link to="/home">homepage</router-link> <router-link :to="top">Hotspot</router-link> <router-link :to="{path:'/abouts'}">About us</router-link> <router-link :to="{name:'aaa'}">AAA</router-link> <router-link :to="{name:'bbb',params:{id:300}}">BBB</router-link> <!-- Displayed Content --> <router-view></router-view> </div> <script src="./vue.js"></script> <script src="./vue-router.js"></script> <script> // Template Content let Home = { template: `<div><span>homepage</span></div>` } let Top = { template: `<div><span>Hotspot</span></div>` } let Abouts = { template: `<div><span>About us</span></div>` } let AAA = { template: `<div><span>AAA</span></div>` } let BBB = { template: `<div><span>BBB{{$route.params.id}}</span></div>` } // Matching rules let router = new VueRouter({ routes: [{ path: '/home', component: Home }, { path: '/top', component: Top }, { path: '/abouts', component: Abouts }, { name: 'aaa', path: '/aaa', component: AAA }, { name: 'bbb', path: '/bbb/:id', component: BBB }] }) let vm = new Vue({ el: '#app', data: { top: '/top' }, router }) </script> </body> </html>
3. Redirection
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div id="app"> <!-- Configuration Path --> <router-link to="/home">homepage</router-link> <router-link to="/top">Hotspot</router-link> <router-link to="/abouts">About us</router-link> <!-- Displayed Content --> <router-view></router-view> </div> <script src="./vue.js"></script> <script src="./vue-router.js"></script> <script> // Template Content let Home = { template: `<div><span>homepage</span></div>` } let Top = { template: `<div><span>Hotspot</span></div>` } let Abouts = { template: `<div><span>About us</span></div>` } // Matching rules let router = new VueRouter({ routes: [{ path: '/home', component: Home }, { path: '/top', component: Top, redirect:'/home' }, { path: '/abouts', component: Abouts }] }) let vm = new Vue({ el: '#app', data: {}, router }) </script> </body> </html>
4. Programmatic Navigation
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div id="app"> <!-- Configuration Path --> <router-link to="/home">homepage</router-link> <router-link :to="top">Hotspot</router-link> <router-link :to="{path:'/abouts'}">About us</router-link> <router-link :to="{name:'aaa'}">AAA</router-link> <router-link :to="{name:'bbb',params:{id:300}}">BBB</router-link> <button @click="fnclick">Programmatic Navigation</button> <!-- Displayed Content --> <router-view></router-view> </div> <script src="./vue.js"></script> <script src="./vue-router.js"></script> <script> // Template Content let Home = { template: `<div><span>homepage</span></div>` } let Top = { template: `<div><span>Hotspot</span></div>` } let Abouts = { template: `<div><span>About us</span></div>` } let AAA = { template: `<div><span>AAA</span></div>` } let BBB = { template: `<div><span>BBB{{$route.params.id}}</span></div>` } // Matching rules let router = new VueRouter({ routes: [{ path: '/home', component: Home }, { path: '/top', component: Top, redirect: '/home' }, { path: '/abouts', component: Abouts }, { name: 'aaa', path: '/aaa', component: AAA }, { name: 'bbb', path: '/bbb/:id', component: BBB }] }) let vm = new Vue({ el: '#app', data: { top: '/top' }, methods: { fnclick() { this.$router.push({ name: 'aaa' }) } }, router }) </script> </body> </html>
5. Routing activation style
The current route has an active class style in the navigation
<a href="#/bj "class=" router-link-exact-active router-link-active ">Beijing</a>
summary
Here we mainly talk about routing, components, and so on. In the next issue, we will talk about animation.