vue-cli
Vue cli installation
npm install -g @vue/cli
If your installation is too slow or unable to install, it is recommended to use cnpm installation, that is, Taobao image installation
npm install -g cnpm -registry=http://registry.npm.taobao.org
cnpm install -g @vue/cli
What exactly is Vue cli?
Command line interface command line interface is commonly known as scaffold
What is npm?
Node Package Manager
It is a tool for node package management and distribution, and has become the standard of unofficial node modules (packages)
See node's notes for details
What is cnpm?
cnpm command tool customized by Taobao
Pull 2 Template for X
npm install ‐ g @vue/cli if you use this command to install cli, vue ‐ cli4 is installed three point one
However, we may need the cli2 template now, so we need to pull down the cli2 template on this basis
Use the following command to pull 2 Template for X
npm install -g @vie/cli-init
Errors often occur when installing Vue cli:
You want to check whether you are running cmd as an administrator
npm clean cache -force
Clear some of the configurations we previously installed in the computer system
C:\Users\an\AppData\Roaming\npm-cache
NPM cache can also delete this folder manually
cli2
How to create a vue-cli2 project
In the actual development, the project directory you create should not have a Chinese directory
Create through the cli2 project initialization command:
vue init webpack XXX //xxx indicates the name of the project file created
Many options need to be configured during creation
Project name: the Project name is generally the same as the name of the project folder you started to create
Project description: Project description
Author: the author defaults to C: \ users \ an Name and mailbox in gitconfig
Vue build :
Select the two versions when Vue is published
-
runtime-compiler
-
Runtime only is a version that is often used in actual development because of its small size and high efficiency
Install vue Router: whether to install vue router, but not temporarily
use ESLint to lint your code:
When y is selected, you need to select the corresponding code specification:
- Direct selection of standard specifications
set up unit tests: almost all unit tests are selected n
setup e2e tests with Nightwatch: indicates whether or not to use nightwatch for end-to-end testing. It is not required, but directly n
yes use NPM
Directory structure in cli2
Both the build and config directories store configuration files about webpack
node_ The modules directory stores the packages of nodes that need to be dependent on
src Directory: the source file you write, where you want to write code in the future
Static directory; Store some static resources, and all the saved contents will be packed into the dist folder intact
gitkeep means that no matter whether there is any content in the static folder, one-step copy operation must be carried out
cli4
Vue-cli3 is developed based on webpack4
vue-cli3 the above design principle: "0 configuration" directly removes the build and config folders
vue-cli3 improves the visual configuration of vue ui commands and makes them more user-friendly
The static folder is removed and a new public folder is added. The index Html is thrown into the directory structure of cli4 in this folder
vue create XXX //XXX indicates the project name
Configure
Ignore the first item first (my personal configuration will be discussed later); There are generally two items:
Default: default configuration (only babel and eslint)
Manually select features: manually configure
Generally, the default configuration of the project is not enough. We choose the second item.
next step
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-icnzmnqo-1627789946292) (C: \ users \ HP \ appdata \ roaming \ typora \ user images \ image-20201028224410122. PNG)]
According to their desired configuration, for reference only
Select the version of vue
Choose a version of Vue.js that you want to start the project with
Select 2 X
next step
Ask if you want to put the configuration in package JSON file. It is recommended to select the first item, In dedicated config files, to create a new configuration file.
next step
Ask whether to save the above configuration as pre configuration, that is, my "jsxj preset" when selecting the configuration in the first step. According to your own wishes, preconfiguration is convenient for creating projects in the future
y or n as you like
The next step is to create. After creating, you can start writing code and delete the default configuration components that do not use some vue s
You can write the required components yourself
npm run serve start service
cli4 small cases
Routing Router
Cognitive routing
Switch and router configuration
Routing is a term in network engineering
Routing is the activity of transmitting information from the source address to the destination through the Internet
You may not be very familiar with routing, but do you all know the router?
Router provides two mechanisms; Routing and forwarding
-
Routing determines the path of a packet from its source to its destination
-
Forwarding is the transfer of data from the input to the appropriate output
There is a very important thing in routing: routing table
Routing table: it is essentially a mapping table
Back end routing and front end routing
Interview question: what is front-end rendering? What is backend rendering?
1. The earliest front-end html+css back-end rendering: PHP, JSP, etc
The web page has been loaded on the server, and the back end just sends the loaded HTML CSS to the user
Back end Routing: the back end processes the mapping relationship between url and page, which is called back-end routing
Disadvantages: the back-end developers are under great pressure and have a heavy workload. html and java code and data are mixed together, which is not conducive to maintenance
2.ajax front end and back end separation: the back end is only responsible for data, not any interface content
Front end to render the page
3. SPA in single page rich application stage:
The main feature is to add front-end routing on the basis of front-end and back-end separation
Each website has only one HTML, and the page will not refresh when changing the url
Implement front-end Routing:
The front-end handles the mapping relationship between url and page, which is the front-end routing
How to change the url without refreshing the page?
There are two means:
-
hash in location
this.$router.hash("path")
-
history mode pushState
this.$router.push("path")
Basic use of Vue router
Vue router is based on Routing and components. Routing is to set access paths and map paths and components one by one
install
npm install vue-router --save
use
Create a router folder under the src folder and create an index JS is used to configure routing
to configure:
- Import routing objects
- Call Vue use(VueRouter)
- Create routing instance
- Mapping configuration of incoming routes in routing instances
- Mount the routing instance in the Vue instance
index.js
//Configure routing related information import Vue from 'vue' import VueRouter from 'vue-router' //Reference the plug-in through use() Vue.use(VueRouter) //Create a vueroter object const routes = [ ] //Configure the relationship between routing and components const router = new VueRouter({ routes }) //Export router export default router
main.js
import Vue from 'vue' import App from './App.vue' //Import router import router from './router/index' Vue.config.productionTip = false new Vue({ router, render: h => h(App), }).$mount('#app')
Configure mapping relationship:
1.Create multiple corresponding components
2. Configure routing mapping
index.js
//Import components import Home from '../components/Home' import About from '../components/About' //Configure routing mapping const routes = [ { path : '/home', component : Home }, { path : '/about', component : About } ]
Use routing
To attribute: used to specify the path to jump
tag attribute: use this attribute to modify the parsed tag style
replace attribute: history is not retained
Active class attribute: a router link active class name will be added to the active route and changed to the name we want
Use the router link tag to jump
<router-link to="/home">home page</router-link> <router-link to="/about">about</router-link>
Use the < router ‐ View > tag to render the components to be loaded
<router‐view></router‐view>
Set mode in the routing instance: 'history' to convert to history mode. The address has no # number
//Configure the relationship between routing and components const router = new VueRouter({ routes, mode : "history" })
Configure route redirection to point to another route location when the page is loaded
//Create a vueroter object const routes = [ //Configure route redirection to point to another route location when the page is loaded { // '/' indicates the page entered when the url is just opened path:"/", redirect : '/home' }, { path : '/home', component : Home }, { path : '/about', component : About } ]
Jump in other ways:
<template> <div> <button @click="homeClick">home page</button> <button @click="about">about</button> <router-view></router-view> </div> </template> <script> export default { name: 'App', components: { }, methods:{ homeClick(){ this.$router.push("home") }, about(){ this.$router.push("about") } } } </script> <style> </style>
Dynamic routing: in some cases, the path of the url may not be fixed, so we need to use dynamic routing (path parameters)
Path (path configuration)
{ path : '/user/:userId', component : User }
App. Jump using the second mode in Vue
<template> <div> <button @click="homeClick">home page</button> <button @click="about">about</button> <button @click="user">user</button> <router-view></router-view> </div> </template> <script> export default { name: 'App', components: { }, methods:{ homeClick(){ this.$router.push("hoeme") }, about(){ this.$router.push("abeout") }, user(){ this.$router.push("user/"+123) } } } </script> <style> </style>
User: then set the calculation property in the corresponding component
Here is r o u t e no yes route is not route is not a router
$route represents the currently active route
$router represents all routes
<template> <div> qqqq {{id}} </div> </template> <script> export default { name: "User", computed :{ id(){ //get data return this.$route.params.userId } } } </script> <style scoped> </style>
Route lazy loading
Benefits: when the current route is executed, the vue file is imported, which is more efficient
const routes = [ { path : '/home', component : ()=>import('../components/Home') } ]
Nested routing of Vue router
For example, on the Home page, you want to access some content through / home/message /home/news. One path needs to map one component, and the two paths also need to map two different components
Second step:
Create the corresponding sub component, and configure the corresponding sub route children attribute configuration in the route mapping table
const routes = [ { path : '/home', component : Home, children:[ { path: "message", //Import subcomponents component: () => import("../components/homeChildren/Message") } ] } ]
App.vue
<template> <div> <button @click="message">news</button> <router-view></router-view> </div> </template> <script> export default { name: 'App', components: { }, methods:{ message(){ this.$router.push("/home/message") } } } </script> <style> </style>
Home. Add label to Vue
<template> <div> qqqq <router-view></router-view> </div> </template> <script> export default { name: "Home" } </script> <style scoped> </style>
Vue router navigation guard
The main purpose is to monitor the jump from where to where
Global front guard
If we want each page to have its own title, we need to use global guard
Add the corresponding meta attribute in the configuration of the routing table, and add the title: "home page"
{ path: "/about", component: ABout, meta : { title : "about" } }
In the index of the route Configuring global pre guard in JS
It is not difficult to understand from the name of global front guard. It is global, that is, it takes effect for all routes in the whole single page application (SPA). Therefore, when a global front guard is defined, this callback will be called before entering each route. If you make an error in judging the jump condition of the route in the callback, The simple point is dead loop... Because you miss a route jump, the guard will always execute it. Therefore, when using the global front guard, you must judge the possible route jump.
//Set up a global navigation guard router.beforeEach(function (to,from,next) { document.title = to.matched[0].meta next(); })
To indicates the routing object to be entered
from indicates the routing object to leave
Next calls this method to enter the next hook
example:
router.beforeEach((to, from, next) => { //Enable lazy loading iView.LoadingBar.start() //Get token const token = getToken() if (!token && to.name !== LOGIN_PAGE_NAME) { // The page that is not logged in and you want to jump to is not a login page next({ name: LOGIN_PAGE_NAME // Jump to login page }) } else if (!token && to.name === LOGIN_PAGE_NAME) { // The page not logged in and to jump to is the login page next() // Jump } else if (token && to.name === LOGIN_PAGE_NAME) { // The page you have logged in and want to jump to is the login page next({ name: 'home' // Jump to the homeName page }) } })
As for the token in the code, the token is a key value pair stored through a cookie
Global post guard (hook)
router.afterEach((to,from) => { //Executed code })
If you understand the global front guard, then the global rear guard is the same thing. Global post guard is a callback that will be executed after each route jump in the whole single page application. Therefore, it is mostly used for the corresponding page operation after route jump. Unlike the global front guard, it will redirect or jump the page in the callback.
As mentioned earlier in the application scenario, the page after the jump is called back to the 0 position of the scroll bar, the page title is updated, the lazy loading is over, and so on
router.afterEach((to, from) => { setTitle(to, router.app) iView.LoadingBar.finish() window.scrollTo(0,0) })
keep-alive
A built-in component in the Vue instance
Every time we return to the previous component page, it is a newly created component
Package the router view with keep alive. At this time, all view components matching the path will be cached, but the content of the secondary route in the current component will not be cached
What if the contents of the secondary route are saved together?
Cancel the redirection of the secondary route
Set the default path for saving path data in the parent component of the secondary route
Add two hook functions to the parent component. These two hook functions will be valid only after keep alive is saved. They will be executed when the current component is active
activated(){ } beforeRouteLeave(){ }
Keep alive adds some attributes
exclude = "User,About" the components will not be kept alive
<keep-alive exclude="User,About"> <router-view></router-view> </keep-alive>
Vue-X
What is Vuex?
Vuex is designed for Vue JS application development state management mode.
It adopts the state of all components of the "centralized storage management" application, and ensures that the state changes in a predictable way with corresponding rules
Vuex is also integrated into Vue's official debugging tool devtools extension, which provides advanced debugging functions such as time travel debugging with zero configuration and import and export of state snapshots.
What is state management?
That is, we may need to use some common data or variables in multiple components, so we can use a common object for centralized storage
Put all these common contents into this object. No matter which component wants to use the contents, it can provide a response
What data does state management manage?
Management status of single page
Vuex is a plug-in
The first step for Vuex is installation
npm install vuex --save or yarn add vuex --save
Vuex basic usage
What does Vuex do? What is state management? Which states need to manage the state of a single page? The most basic use of Vuex is state
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-lhsl5gc8-1627789946295) (C: \ users \ HP \ appdata \ roaming \ typora \ typora user images \ image-20201105185601832. PNG)]
Create a folder store
Create an index. In this folder js
store/index.js
import Vue from 'vue' import Vuex from 'vuex' //Install plug-ins Vue.use(Vuex) //create object var store = new Vuex.Store({ //Store data state:{}, //Storage synchronization method mutations:{}, //Storing asynchronous methods actions:{}, //Calculation properties getters:{}, //Template separation modules:{} }) //Import store export default store
main.js
import Vue from 'vue' import App from './App.vue' //In main JS import store from './store' Vue.config.productionTip = false new Vue({ store, render: h => h(App), }).$mount('#app')
How to modify data in state
You need to use the changes attribute to define some methods to change the state
But how do we use the methods?
this.$store.commit('add ') to call the add method in changes
Five core concepts in Vuex:
State: a single state tree that holds the public state
We only create one store warehouse in Vuex, and we don't need to create multiple warehouses
mutations:
The only way to change the state in Vuex is to submit it to changes
It is mainly divided into two parts:
Event type
Callback function, where the first parameter in the function is our state content
this.$store.commit('add ') to call the add method in changes
Another submission method is provided in Vue:
this.$store.commit({ type:'add', user })
The value received in mutations is the value of an object type, and two attributes are stored in it: type user
store/index.js
var store = new Vuex.store({ //Store data state:{ count : 0 }, //Storage synchronization method mutations:{ add(state,value){ state.count = value; } }, //Storing asynchronous methods actions:{}, //Calculation properties getters:{}, //Template separation modules:{} })
app.vue
<template> <div id="app"> <!--Get vuex in state Value of--> {{$store.state.count}} </div> </template> <script> export default { name: 'App', components: { }, created(){ //Call the add method in mutations and pass in the data this.$store.commit('add',2) } } </script> <style> </style>
Rules for Mutations response
The content in state is added to the response expression
In the state data, each piece of data will have a DEP, which is a listener
If you want this data to be responsive, you must define it in state
Vue. Set (data source to be changed, specific data to be changed, reassigned value)
All the methods defined in the variables are synchronous methods, and asynchronous operations are not allowed
getters:
Similar to calculated properties in components
When a certain data needs to undergo a series of changes before it can be used, we need to use getters
actions: similar to mutations, one resolves synchronization and the other resolves asynchrony
Resolve asynchronous operations
modules:
Partition module
Get the state status in the module:
$store.state. Module name Status data
Get the changes status in the module:
this.$store.commit('method in module ') method names in all modules cannot be the same
Get the calculation attribute in getters in the module:
unt = value;
}
},
//Storing asynchronous methods
actions:{},
//Calculation properties
getters:{},
//Template separation
modules:{}
})
app.vue ```vue <template> <div id="app"> <!--Get vuex in state Value of--> {{$store.state.count}} </div> </template> <script> export default { name: 'App', components: { }, created(){ //Call the add method in mutations and pass in the data this.$store.commit('add',2) } } </script> <style> </style>
Rules for Mutations response
The content in state is added to the response expression
In the state data, each piece of data will have a DEP, which is a listener
If you want this data to be responsive, you must define it in state
Vue. Set (data source to be changed, specific data to be changed, reassigned value)
All the methods defined in the variables are synchronous methods, and asynchronous operations are not allowed
getters:
Similar to calculated properties in components
When a certain data needs to undergo a series of changes before it can be used, we need to use getters
actions: similar to mutations, one resolves synchronization and the other resolves asynchrony
Resolve asynchronous operations
modules:
Partition module
Get the state status in the module:
$store.state. Module name Status data
Get the changes status in the module:
this.$store.commit('method in module ') method names in all modules cannot be the same
Get the calculation attribute in getters in the module:
this.$store.getters. Calculated attribute name