Vue of actual combat
1. The introductions to the Vue
Progressive JavaScript Framework – from the official website
# incremental
1.Easy to use HTML CSS javascript 2.Developing front-end pages efficiently is very efficient 3.Flexible development flexible diversity# summary
Vue is a javascript framework
Backend server developer:
Vue's progressive javascript framework makes it easy to bind data and views by manipulating very little DOM, or even any DOM elements in the page. HTMLCSS ->javascript -----> Jquery ----> AngularJS -----> Vue # VueCopy the code
2. Introduction to the Vue
2.1 download Vuejs
// Version:<! -- Development environment version, including helpful command line warnings --><script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
// Production version:<! -- Production environment version, optimized size and speed --><script src="https://cdn.jsdelivr.net/npm/vue"></script>
Copy the code
2.2 Vue the first entry application
<div id="app">
{{ msg }} {{username}} {{pwd}}
<br>
<span>
{{ username }}
<h1>{{ msg }}</h1>
</span>
</div>
<! -- introduction of vue. Js - >
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
const app = new Vue({
el:"#app".// Element is used to define a scope for a Vue instance
data: {// This is used to define some data for the Vue instance
msg:"Welcome to HAust and look forward to your joining us!".username:"hello Vue!".pwd :"12345",}});</script>
Copy the code
# summary:
1. The EL attribute in vUE instance (object) : represents the scope of vUE in the future, the syntax of VUE can be used within the scope of VUE. To bind Vue instance data, the bound data can be retrieved by {{variable name}} in Vue scope 3. In the use of {{}} to obtain data in the data, can be written in the {{}} expression, operator, call related method, as well as the logic operation and so on 4. El properties can be written in any CSS selector/jquery selector, but in the use of Vue development is recommended to use id selectorsCopy the code
3. V – – HTML text and v
3.1 v – text
V-text: Takes the data from the data and renders the data as text inside the specified tag, similar to innerText in javascript
<div id="app" class="aa">
<span >{{ message }}</span>
<span v-text="message"></span>
</div>
<! -- introduction of vue. Js - >
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
const app = new Vue({
el:"#app".data: {message:"Welcome to Haust."}})</script>
Copy the code
1. The difference between {{}}(interpolation) and V-text is that a. The value of V-text overwrites the original data of the label. Interpolation does not overwrite the original data b of the label. Using V-text can avoid interpolation flicker in poor network environmentCopy the code
3.2 v – HTML
V-html: Takes the data from the data and parses the HTML tag inside the rendered tag, similar to innerHTML in javascript
<div id="app" class="aa">
<span>{{message}}</span>
<br>
<span v-text="message"></span>
<br>
<span v-html="message">xxxxxx</span>
</div>
<! -- introduction of vue. Js - >
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
const app = new Vue({
el:"#app".data: {message:"}})</script>
Copy the code
4. Event binding in VUE (V-ON)
4.1 Basic Syntax for Binding Events
<div id="app">
<h2>{{message}}</h2>
<h2 v-text="message"></h2>
<h2>Age :{{age}}</h2>
<br>
<input type="button" value="Click on me to change my age." v-on:click="changeage">
</div>
<! -- introduction of vue. Js - >
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
const app = new Vue({
el:"#app".data: {message:"Hello, welcome to Baizhi Class!".age:23,},methods: {//methods are used to define the time in vUE
changeage:function(){
alert('Click trigger'); }}})</script>
Copy the code
# summary:
Event source: event occurs DOM element event: specific action occurs click.... The event handler after a particular listener action is usually function 1 in JS. Binding events in VUE is done with the V-ON directive v-on: event names such as V-ON :click 2. In the assignment statement of v-ON: event name is the name of the function that triggered the call at the current time 3. The functions of events in vUE are uniformly defined in the methods property of vUE instances 4. In the event defined by VUE, this refers to the current VUE instance and can be used in the event to obtain the relevant data of the VUE instanceCopy the code
Simplified syntax for events in 4.2 Vue
<div id="app">
<h2>{{ age }}</h2>
<input type="button" value="Change age by V-ON event +1 each time" v-on:click="changeage">
<input type="button" value="Change age by @ binding time each time -1" @click="editage">
</div>
<! -- introduction of vue. Js - >
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
const app = new Vue({
el:"#app".//element: Specifies the vUE scope
data: {age:23,},//data: used to define data related to the VUE instance
methods: {changeage:function(){
this.age++;
},
editage:function(){
this.age--; }}//methods: Methods used to define event handlers
});
</script>
Copy the code
# summary:
1. When binding events in VUE in the future, the @ symbol can be used to simplify v-ON event bindingCopy the code
4.3 Vue event function can be written in two ways
<div id="app">
<span>{{count}}</span>
<input type="button" value=Change the value of count @click="changecount">
</div>
<! -- introduction of vue. Js - >
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
const app = new Vue({
el:"#app".data: {count:1,},methods: {/*changecount:function(){ this.count++; } * /
changecount(){
this.count++; }}});</script>
Copy the code
# summary:
1. There are two ways to write event definition in Vue :function(){} and function name :(){}Copy the code
4.4 Vue Event Parameter Transfer
<div id="app">
<span>{{count}}</span>
<input type="button" value="Change count to the specified value" @click="changecount(23,'xiaohei')">
</div>
<! -- introduction of vue. Js - >
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
const app = new Vue({
el:"#app".data: {count:1,},methods: {/ / define changecount
changecount(count,name){
this.count = count; alert(name); }}});</script>
Copy the code
# summary:
1. When using the event, you can directly pass parameters to the event in the event call, and define parameters to receive and pass by defining corresponding variables in the eventCopy the code
5.v-show v-if v-bind
5.1 v – show
V-show: controls whether a tag element on a page displays the underlying use of the display property
<div id="app">
<! -- v-show: used to show or hide tags -->
<h2 v-show="false">Baizhi Education welcomes you to join us!</h2>
<h2 v-show="show">This is the variable defined in VUE true!</h2>
<input type="button" value="Show hidden tags" @click="showmsg">
</div>
<! -- introduction of vue. Js - >
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
const app = new Vue({
el:"#app".data: {show:false,},methods: {// Define the time
showmsg(){
this.show = !this.show; }}})</script>
Copy the code
# summary
1. In v-show, you can write Boolean values directly to control the display of elements. You can also use variables to control the show and hide of tags. In V-show, you can use Boolean expressions to control the display of tagsCopy the code
5.2 v – the if
V-if: Used to control whether the page element displays the underlying control that the DOM element manipulates the DOM
<div id="app">
<h2 v-if="false">Best known education</h2>
<h2 v-if="show">Baizhi Education welcomes you to join us</h2>
</div>
<! -- introduction of vue. Js - >
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
const app = new Vue({
el:"#app".data: {show:false
},
methods: {}});</script>
Copy the code
5.3 v – bind
V-bind: Used to bind the attributes of the tag to dynamically modify the attributes of the tag through vUE
<div id="app">
<img width="300" v-bind:title="msg" v-bind:class="{aa:showCss}" src="baizhilogo.jpg" alt="">
</div>
<! -- introduction of vue. Js - >
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
const app = new Vue({
el:"#app".data: {msg:"csp!!!!".showCss:true,},methods: {}})</script>
Copy the code
5.4 V-bind simplified writing
Vue provides a simplified way to bind tag attributes in the future, such as V-bind: attribute name after simplification: attribute name
<div id="app">
<img width="300" :title="msg" :class="{aa:showCss}" :src="src" alt="">
<input type="button" value="Dynamic control add style" @click="addCss">
<input type="button" value="Change the picture" @click="changeSrc">
</div>
<! -- introduction of vue. Js - >
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
const app = new Vue({
el:"#app".data: {msg:"hello".showCss:true.src:"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1583490365568&di=52a82bd614cd4030f97ada9441bb2d0e&i mgtype=0&src=http%3A%2F%2Fimg.kanzhun.com%2Fimages%2Flogo%2F20160714%2F820a68f65b4e4a3634085055779c000c.jpg"
},
methods: {addCss(){
this.showCss= !this.showCss;
},
changeSrc(){
this.src = "Https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=1925088662, & FM = 26 & gp = 0. 1336364220 JPG"; }}})</script>
Copy the code
6. V – for use
V-for: used to iterate over objects (arrays are also a type of object)
<div id="app">
<span>{{ user.name }} {{ user.age }}</span>
<br>
<! Pass through the object with v-for -->
<span v-for="(value,key,index) in user">
{{index}} : {{key}} : {{value}}
</span>
<! Select * from v- >
<ul>
<li v-for="a,index in arr" >
{{index}} {{a}}
</li>
</ul>
<! Select * from vue; select * from vue; select * from vue;
<ul>
<li v-for="user,index in users" :key="user.id">
{{index+1}} {{ user.name }} === {{ user.age }} ==== {{ user.content }}
</li>
</ul>
</div>
<! - introduction of vue -- -- >
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
const app = new Vue({
el: "#app".data: {
user: {name:"csp".age:22},
arr: ["Xiyuan Campus"."New Century Campus"."Hkust"].users:[
{id:"1".name:"csp".age:23.content:"I'm still some rich boy!"},
{id:"2".name:"Java small white".age:23.content:"Nothing has changed!}},],methods: {}});</script>
Copy the code
# summary
1. When using V-for, note the following :key Provides a unique key for internal reuse and sorting of vUECopy the code
7. V-model two-way binding
V-model: The value of the binding label element is consistent with the data data in the VUE instance object, so as to realize the two-way data binding mechanism
<div id="app">
<input type="text" v-model="message">
<span>{{message}}</span>
<hr>
<input type="button" value="Change Data median" @click="changeValue">
</div>
<! - introduction of vue -- -- >
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
const app = new Vue({
el: "#app".data: {
message:""
},
methods: {
changeValue(){
this.message='hello! '; }}});</script>
Copy the code
# summary
Two-way binding of data can be realized by using V-model instruction 2. So-called two-way binding: Data changes in a form cause data changes in vUE instance data changes in a VUE instance data changes in a form are called two-way binding
# MVVM architecture bidirectional binding mechanism
Model: Data Vue instance binding data VM: ViewModel listener
View: data displayed on a pageCopy the code
8. Event modifiers
Modifier: Used in conjunction with events to determine the condition under which an event is triggered or to prevent an event from being triggered
# 1. Common event modifiers
.stop .prevent .capture .self .once .passiveCopy the code
8.1 Stop event modifier
Used to prevent events from bubbling
<div id="app">
<div class="aa" @click="divClick">
<! -- used to prevent events from bubbling -->
<input type="button" value="Button" @click.stop="btnClick">
</div>
</div>
<! - introduction of vue -- -- >
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
const app = new Vue({
el: "#app".data: {},
methods: {
btnClick(){
alert('Button is clicked');
},
divClick(){
alert('Div is clicked'); }}});</script>
Copy the code
8.2 Prevent event modifier
Used to block the default behavior of the tag
<! -- The default behavior used to block events -->
<a href="http://www.baizhibest.com/" @click.prevent="aClick">Hello World</a>
Copy the code
8.3 self Event modifier
Events used to trigger events for the current tag ===========> Events that only trigger specific actions on their own tags care only about events triggered on their own tags and do not listen for event bubbling
<! -- Triggers only events for the tag itself -->
<div class="aa" @click.self="divClick">
<! -- used to prevent events from bubbling -->
<input type="button" value="Button" @click.stop="btnClick">
<input type="button" value="Button 1" @click="btnClick1">
</div>
Copy the code
8.4 Once Event modifier
Once: Causes the specified event to fire only once
<! --.prevent: used to prevent the default behavior of events. Once: used to execute a particular event only once -->
<a href="http://www.baizhibest.com/" @click.prevent.once="aClick">Hello World</a>
Copy the code
9. Key modifier
Purpose: A modifier used to bind key events in a keyboard and to modify a specific key event
# Key modifier
.enter.tab. Delete (capture "delete" and "backspace" keys).ESC.space.up.down.left.rightCopy the code
9.1 Enter Enter
The event used to trigger after the enter key is triggered
<input type="text" v-model="msg" @keyup.enter="keyups">
Copy the code
9.2 the TAB key
Used to capture when the TAB key executes until the current TAB is triggered
<input type="text" @keyup.tab="keytabs">
Copy the code
10. Basic use of Axios
10.1 the introduction
Axios is an asynchronous request technology, the core function is used to send asynchronous requests in the page, and obtain the corresponding data in the page rendering partial update technology Ajax
10.2 Axios first program
Chinese website: www.kancloud.cn/yunye/axios…
Installation: unpkg.com/axios/dist/…
10.2.1 GET Request
// Send a GET request
axios.get("http://localhost:8989/user/findAll? name=xiaochen").then(function(response){
console.log(response.data);
}).catch(function(err){
console.log(err);
});
Copy the code
10.2.2 POST Requests
// Send a POST request
axios.post("http://localhost:8989/user/save", {username:"xiaochen".age:23.email:"[email protected]".phone:13260426185
}).then(function(response){
console.log(response.data);
}).catch(function(err){
console.log(err);
});
Copy the code
10.2.3 Axios Concurrent Requests
Concurrent requests: Multiple requests are sent to the back-end service interface at the same time, and the result of each request is processed centrally
//1. Create a query for all requests
function findAll(){
return axios.get("http://localhost:8989/user/findAll? name=csp");
}
//2. Create a save request
function save(){
return axios.post("http://localhost:8989/user/save", {username:"csp".age:22.email:"[email protected]".phone:13260426185
});
}
//3. Execute concurrently
axios.all([findAll(),save()]).then(
axios.spread(function(res1,res2){ // It is used to aggregate the responses of a group of functions
console.log(res1.data);
console.log(res2.data); }));// To send a set of concurrent requests
Copy the code
11. Vue life cycle
Lifecycle hooks ====> Lifecycle functions
# Vue lifecycle summary1.Initialization phasebeforeCreate(){ //1. The first function in the lifecycle. When this function is executed, the Vue instance only completes the binding of its own events and the initialization of the lifecycle function, and the Vue instance has no Data EL Methods attribute
console.log("beforeCreate: "+this.msg);
},
created(){ //2. The second function in the lifecycle, which is executed when the Vue instance has already initialized the data attribute and related methods in methods
console.log("created: "+this.msg);
},
beforeMount(){//3. The third function in the lifecycle, which is executed when Vue compiles the scope specified in El as a template
console.log("beforeMount: "+document.getElementById("sp").innerText);
},
mounted(){//4. The fourth function in the lifecycle, which has rendered data to the interface and updated the page in the process of execution
console.log("Mounted: "+document.getElementById("sp").innerText);
}
2.Operation phasebeforeUpdate(){//5. The fifth function in the lifecycle is executed when the data in the data has changed. This event is executed only when the data in the Vue instance has changed
console.log("beforeUpdate:"+this.msg);
console.log("beforeUpdate:"+document.getElementById("sp").innerText);
},
updated(){ //6. The sixth function in the life cycle. This function is executed when the data in the data changes and the data in the page changes as well
console.log("updated:"+this.msg);
console.log("updated:"+document.getElementById("sp").innerText);
},
3.Destruction of phasebeforeDestory(){// The methods componet data in Vue are not destroyed when this function is executed
},
destoryed(){ //8. The eighth function of the lifecycle, when executed, the Vue instance is completely destroyed
}
Copy the code
12. Components in Vue
12.1 Component Functions
Component functions: Used to reduce the amount of code in the Vue instance object. In the future, in the process of using Vue development, you can divide the page into different components according to the business functions, and then complete the layout of the whole page by multiple components, which is convenient for the page management when using Vue development in the future, and convenient for developers to maintain.
12.2 Using Components
12.2.1 Registering Global Components
Note: A global component is registered with a Vue instance and can later be used within the scope of any Vue instance
//1. Develop global components
Vue.component('login', {template:'
User login
});
//2. Use global components within the scope of Vue instances
<login></login>
Copy the code
# note:
1.Vue.component is used to develop global components. Parameter 1: component name Parameter 2: component configuration {} template: "is used to write the HTML code template of the component must have only one root element 2. Use global components according to their names within the scope of the Vue. 3. If you use a hump name during the component registration process, you must lowercase all the words of the hump in the - line for useCopy the code
12.2.2 Partial Component Registration
Note: Components are registered by registering them with a component property in the corresponding Vue instance. This method does not accumulate Vue instances
- The first type of development
// Local component login template declaration
let login ={ // Specify the local component name
template:'
User login
'
};
const app = new Vue({
el: "#app".data: {},
methods: {},
components: {// To register local components
login:login // Registry component}});// Local components are used within the scope of Vue instances
<login></login>
Copy the code
-
Second development mode
//1. Declare the local component template tag. Note: Declare it outside the scope of the Vue instance <template id="loginTemplate"> <h1>The user login</h1> </template> //2. Define variables to save template configuration objects let login ={ // Specify the local component name template:'#loginTemplate' // Use the custom template tag selector }; //3. Register components const app = new Vue({ el: "#app".data: {}, methods: {}, components: {// To register local components login:login // Registry component}});//4. Local components are used within the scope of Vue instances <login></login> Copy the code
12.3 Use of Prop
Function :props is used to pass static or dynamic data to a component
12.3.1 Pass static data inside a component by declaring it on it
//1. Declare the component template configuration object
let login = {
template:"< div > < h1 > welcome: age: {{userName}} {{age}} < / h1 > < / div >".props: ['userName'.'age'] // the props function is used to receive data passed through the component label when using the component
}
//2. Register components
const app = new Vue({
el: "#app".data: {},
methods: {},
components:{
login // Component registration}});//3. Complete data transfer through components
<login user-name="csp" age="22"></login>
Copy the code
# summary:
Multiple properties and corresponding data can be defined on a component. 2. Internal components can use props array life Multiple property names defined on a component can be obtained by {{property name}} on a componentCopy the code
12.3.2 Pass dynamic data internally to components by declaring it on them
//1. Declare the component template object
const login = {
template:{{age}}'.props: ['name'.'age']}//2. Register local components
const app = new Vue({
el: "#app".data: {
username:"csp".age:22
},
methods: {},
components:{
login // Register the component}});//3. Use components
<login :name="username" :age="age"></login> // Use v-bind to bind the data attribute in the Vue instance. If the data attribute changes in the future, the internal data of the component changes accordingly
Copy the code
12.3.3 Unidirectional Data flow of Prop
One-way data flow: All prop forms a ** one-way downlink binding between their parent prop ** : updates to the parent prop flow down to the child, but not the other way around.
All prop forms a one-way downlink binding between their parent prop: updates to the parent prop flow down to the child, but not the other way around. This prevents accidental changes in the state of the parent component from the child, which can make the data flow of your application difficult to understand.
Additionally, every time the parent component is updated, all prop in the child component will be refreshed to the latest value. This means that you should not change a prop inside a child component. If you do, Vue will issue a warning in the browser console. — from the official website
12.4 Defining data and event usage in components
1. Define the data belonging to the component
// The configuration object declared by the component
const login = {
template:'<div><h1>{{ msg }} Hello World</h1><ul><li v-for="item,index in lists">{{ index }}{{ item }}</li></ul></div>'.data(){ // The data used to define components is retrieved directly by interpolation in the templateHTML code
return {
msg:"hello".lists: ['java'.'spring'.'springboot']}// The component's own internal data}}Copy the code
2. Event definitions in components
const login={
template:@click="change">' ' .data(){
return {
name:'csp'
};
},
methods: {change(){
alert(this.name)
alert('Trigger event'); }}}Copy the code
# summary
1. Defining events in components is basically the same as defining events in Vue. Add @event name = function name to the corresponding HTML code inside components. Use the methods attribute inside the component to define the corresponding event function, where this refers to the instance of the current componentCopy the code
12.5 Pass events to and call modified events in child components
Calls to related events passed from a child component must be called using this.$emit(' function name ')
//1. Declare the component
const login = {
template:
Hello World {{uname}}
.data(){
return {
uname:this.name
}
},
props: ['name'].methods: {change(){
// Call the vue instance function
this.$emit('aaa'); // This.$emit(' function name call ') is used when calling other functions passed by the component.}}}//2. Register components
const app = new Vue({
el: "#app".data: {
username:"csp"
},
methods: {
findAll(){ // An event function passes this function to the child component
alert('Function defined in Vue instance'); }},components:{
login,// Component registration}});//3. Use components
<login @find="findAll"></login> //=====> Use this.$emit('find') inside the component
Copy the code
13.Vue Middle Route (VueRouter)
13.1 the routing
Routing: according to the path of the request according to certain routing rules for request forwarding so as to help us achieve unified request management
13.2 role
Used to dynamically switch between components in vUE
13.3 Using Routes
-
The introduction of the routing
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script> / / the vue routing js Copy the code
-
Creating a component object
// Declare the component template const login = { template:'< h1 > login < / h1 >' }; const register = { template:'< h1 > register < / h1 >' }; Copy the code
-
Define rules for routing objects
// Create a routing object const router = new VueRouter({ routes:[ {path:'/login'.component:login}, //path: indicates the route path. Component: indicates the component corresponding to the path {path:'/register'.component:register} ] }); Copy the code
-
Register the routing object with the VUE instance
const app = new Vue({ el: "#app".data: { username:"csp",},methods: {}, router:router // Set the route object }); Copy the code
-
Displays routed components on the page
<! -- Display routing components --> <router-view></router-view> Copy the code
-
Switch routes based on connections
<a href="#/login">Let me login</a> <a href="#/register">Let me register</a> Copy the code
13.4 the router – use the link
Purpose: To replace the use of a label when switching routes
Benefits: You can automatically add routes to paths
<router-link to="/login" tag="button">I want to login</router-link>
<router-link to="/register" tag="button">Let me register</router-link>
Copy the code
# summary:
1. Router-link is used to replace tag A to implement route switchover. The advantage is that the route path is directly written without #Copy the code
13.5 Default Route
What it does: Displays a default component on first entry
const router = new VueRouter({
routes: [//{ path:'/',component:login},
{ path:'/'.redirect:'/login'}, //redirect: This is recommended when the default route "/" is accessed
{ path:'/login'.component:login},
{ path:'/register'.component:register},
]
});
Copy the code
13.6 Transferring Parameters in Routes
- The first way to pass parameters is the traditional way
-
Through? Concatenation parameter in sign form
<router-link to="/login? id=21&name=zhangsan">I want to login</router-link> Copy the code
-
Component to get parameters
const login = { template:'
User login
'.data(){return {}}, methods: {},created(){ console.log("= = = = = = = = = = = = = >"+this.$route.query.id+"= = = = = = >"+this.$route.query.name); }};Copy the code
- The second way to pass parameters is restful
-
Pass parameters by using a path
<router-link to="/register/24/csp"> I want to register </router-link>var router = new VueRouter({ routes:[ {path:'/register/:id/:name'.component:register} // Define the path to get the corresponding parameters]});Copy the code
-
Component to get parameters
const register = { template:{{$route.params.name}}'.created(){ console.log("Id in registered component:"+this.$route.params.id+this.$route.params.name); }};Copy the code
13.7 Nested routine by
-
Declare the outermost and inner routes
<template id="product"> <div> <h1>Commodity management</h1> <router-link to="/product/add">Goods to add</router-link> <router-link to="/product/edit">Commodities editor</router-link> <router-view></router-view> </div> </template> // Declare the component template const product={ template:'#product' }; const add = { template:'
Merchandise added
' }; const edit = { template:'Merchandise editor
' }; Copy the code -
Creating a routing object contains nested routes
const router = new VueRouter({ routes:[ { path:'/product'.component:product, children:[ {path:'add'.component: add}, {path:'edit'.component: edit}, ] }, ] }); Copy the code
-
Registering a routing Object
const app = new Vue({ el: "#app".data: {}, methods: {}, router,// Define the routing object }); Copy the code
-
Test the routing
<router-link to="/product">Commodity management</router-link> <router-view></router-view> Copy the code
Vue CLI scaffolding
14.1 What is the CLI
The command line interface (CLI) was the most widely used user interface before the popularization of the GRAPHICAL user interface (GUI). It usually does not support the mouse. Users input commands through the keyboard, and the computer executes the commands after receiving them. Some call it CUI (Character User Interface)
14.2 What is the Vue CLI
Vue CLI is a complete system for rapid development based on Vue. Js. Using Vue scaffolding, the page we developed would be a complete system.
14.3 Vue CLI Advantages
-
Build interactive project scaffolding through VUE-CLI. Bootstrap CSS JS jquery JS You can download related dependencies by running commands
-
Vuejs vuerouter axios(one command) Quick start zero configuration prototype development vue page via @vue/cli + @vue/cli-service-global
-
A runtime dependency (@vue/cli-service) that:
- Can upgrade A command
- Built on WebPack with reasonable default configuration; Webpack project package compiled project source === => deployed to the server for direct use
- It can be configured through the configuration file in the project; The default configuration file, by modifying the default configuration file to achieve their desired project environment
- Extensions can be made through plug-ins. vue v-charts elementui
-
A rich collection of official plug-ins that integrate the best tools in the front-end ecosystem. Nodejs(tomcat) Vue VueRouter webpack yarn
-
A fully graphical user interface for creating and managing vue.js projects
14.4 Vue CLI Installation
1. Environment preparation
# 1. Download the nodejs
Windows system: http://nodejs.cn/download/. Msi installation package (exe) designated installation location. Zip (zip) direct decompression MAC OS system specified directory: .pkg Installation package format Automatically configures the environment variable.tar.gz(compressed package)
#2. Configure the nodeJS environment variable
Windows: 1. Right-click properties ----> Advanced properties ----> Environment Variables and add the following configuration: NODE_HOME= NodeJS installation directory PATH = XXXX; %NODE_HOME% 2. Macos recommended use. PKG installation directly configure node environment #3. Node -v #4. NPM Introduction Node Package Mangager NodeJS package management tool Front-end mainstream technology NPM for unified management maven management Java backend relies on remote repository (central repository) Ali Cloud image NPM management front-end system relies on remote warehouse (central warehouse) to configure Taobao mirror #5. Configuration taobao mirror NPM config set registry https://registry.npm.taobao.org NPM config get registry
#6. Configure NPM download dependency locations
windows: npm config set cache "D:\nodereps\npm-cache" npm config set prefix "D:\nodereps\npm_global" mac os: npm config set cache "/Users/chenyannan/dev/nodereps" npm config set prefix "/Users/chenyannan/dev/nodereps"
#7. Verify nodeJS environment configuration
npm config ls ; userconfig /Users/chenyannan/.npmrc cache = "/Users/chenyannan/dev/nodereps" prefix = "/Users/chenyannan/dev/nodereps" registry = "https://registry.npm.taobao.org/"Copy the code
2. Install scaffolding
#0. Unload scaffolding
NPM uninstall -g@vue /cli // Uninstall 3.x version scaffolding NPM uninstall -g vue-cli // Uninstall 2.x version scaffolding
#1.Vue Cli official website
https://cli.vuejs.org/zh/guide/
#2. Install vue Cli
npm install -g vue-cli
Copy the code
3. The first VUE scaffolding project
# 1. Create vue scaffolding first project
Vue init webpack project name # 2. Create the first project hello -------------> project name -build -------------> to use webpack package using build dependency -config -- -- -- -- -- -- -- -- -- -- -- -- -- > used to do the whole project configuration directory - node_modules -- -- -- -- -- - > used to manage projects use dependency - SRC -- -- -- -- -- - > writing vue source code [key] + assets -- -- -- -- -- - > used to store static resource [key] Components used to write -- -- -- -- -- - > the Vue components [key] the router -- -- -- -- -- - > the path [key] App. Used to configure the project Vue -- -- -- -- -- - > project root. [key] the main component of js -- -- -- -- -- - > project main entry [key] - static -- -- -- -- -- - > other static - babelrc -- -- -- -- -- - > will turn es5 running es6 grammar - editorconfig -- -- -- -- -- - edit configuration - > project. Gitignore -- -- -- -- -- - > the git version control ignore files -.postcsrc. Js ------> source code related js-index.html ------> project home -package.json ------> Similar to PAM.xml dependency management jquery Manual modification is not recommended -package-lock.json ----> Lock package.json - readme. md ----> Project Description file
# 3. How to run execution in the project root directory
NPM start runs the front-end system
# 4. How do I access the project
http://localhost:8081
# 5.Vue Cli project development mode
VueCli's development method is to develop a business function module corresponding to one component in the project. In the future, multiple components can be combined together to form a front-end system. In the future, when using the Vue Cli for development, instead of writing HTML, you will write component by component (the file ending with the suffix. Vue), and the Vue Cli will compile the component into running HTML files when packagingCopy the code
4. How to develop Vue scaffolding
Note: In the Vue CLI everything is a component
15. Use Axios in scaffolding
15.1 installation axios
# 1. Install AXIOS
npm install axios --save-dev npm install vue # 2. Configure main.js to import axios from 'axios';
Vue.prototype.$http=axios;
# 3. Use Axios
In the position of the need to send an asynchronous request, enclosing $HTTP. Get (" url "). Then ((res) = > {}) enclosing $HTTP. Post (" url "). Then ((res) = > {})Copy the code
16.Vue Cli scaffolding project packaging and deployment
# 1. Run the following command in the project root directory:
vue run build
Note: Vue scaffolding packaged items must be running on the server and cannot be run directly by double clicking
# 2. Changes in the current project after packaging
After packaging, the project presents the Dist directory, which is the Vue scaffolding project production directory or direct deployment directory
# 3.
Copy the code