Daily learning: scaffold vueCli, arrow function, front-end routing, vue router, dynamic routing and parameter transfer, navigation guard

Scaffold vueCli

  1. vueCli facilitates the rapid establishment of vue development environment and corresponding webpack configuration. The pre dependencies are node, npm and webpack. Manual use of webpack requires manual introduction of various loader s and plugin s, and handling the compatibility of versions;
// View version
node -v,npm -v,webpack -v
// Specify the domestic image, and then use cnpm to install it
npm install -g cnpm --registry=https://registry.npm.taobao.org
// Install vuecli in versions 2 and 3. If the installation fails, use npm cache clean --force, or run cmd as an administrator, or delete the NPM cache folder
npm install -g @vue/cli,vue --version
// To use 2 in vuecli3, you need to pull the template of vuecli2
npm install -g @vue/cli-init 
  1. Create a project using vueCli 2, execute Vue init webpack my project, and then specify the project name, description, author, build mode (runtime compile or runtime only), whether to install es lint (code detection), single test, end-to-end, select package management mode (npm), etc. in the interactive command;
In the created project main.js: Vue.config.productionTip = false Indicates whether the prompt is displayed at runtime
build Mode: the difference is only in main.js,Direct use is recommended runtime only Mode, smaller source code and higher operation efficiency
	runtime compile of main.js: 
		new Vue({
  			el: '#app',
  			components: { App },
  			template: '<App/>'
		The render pass is: template -> ast Syntax tree -> render() -> virtual dom -> UI
	runtime only of main.js: 
		new Vue({
			el: '#app',
			// h is the code of createElement, so it is createElement (tag name, {attribute}, [content]), and createElement can continue in the content
			render: h=>h(App)
		Render pass: render() -> virtual dom -> UI
  1. Node provides a javascript running environment, which can directly execute JS files. Use the command node xxx.js (similar to the function of the browser) to execute npm run build in the application generated by cli2. In essence, execute node build/build.js, that is, run the build.js file. The project directory generated by cli2 is as follows;
build and config All webpack to configure,
node_modules Saved items are project dependent node package,
src Is the source code directory,
static Static resources are stored and will be moved to after packaging dist Table of contents (note and) src/assets Static resource packaging rules under are different)
.babelrc Will be es6 Turn into es5 Configuration file for
.editorconfig Constraint code style, such as indent, number of spaces, etc
package.json Management dependent node package,among ^ Indicates that the last minor version number can be changed, which is greater than or equal to the specified value,~ Indicates that the version number in the middle is variable
package-lock.json The record is package.json in node package Real version
  1. Use cli3 to create a project. The command Vue create my project is characterized by reducing and hiding the configuration. You can start a graphical application (view and modify the configuration) through vue ui, or view the configuration in node modules. If you want to modify the configuration manually, create a vue.config.js file in the root directory, in which module.export = {} Write the modified configuration;
vueCli3 Is based on webpack4,and vueCli2 Is based on webpack3
	Is 0 configuration, removed build,config Etc. configuration directory
	Provided vue ui Visual configuration of
	Removed static Folder, new public Folder (similar) static)
// main.js,. $mount('#app') is equivalent to el: '#app'
new Vue({
  render: h => h(App),

Arrow function

  1. Arrow function is a shorthand syntax for es6 defining a function, (parameter list) = > {...}. When there is only one parameter, parentheses can be omitted. When there is only one line of statements in the function, braces can be omitted, and this line will be returned automatically. If there is no return, return undefined;
// There is only one parameter and only one line of code in the method body. return undefined automatically
const arrowFuncA = param => console.log("this is arrow funcA!");
  1. This in the arrow function refers to this in the nearest scope. In the following example, the first this prints window and the second this prints obj, because the first setTimeout writing method will pass in window by default, while the second writing method will not;
const obj = {
		setTimeout(function () {

Front end routing vue router

  1. Page routing goes through the stage of back-end routing, front-end and back-end separation, and finally to single page application. Single page application refers to that there is only one html, css and js file in the application, and different vue components are combined for display with the change of url. Then the mapping relationship and switching display logic between url and components are called front-end routing;
Back end routing, using jsp Technology, different url Request to different controller,Return different jsp Page, seo More friendly
 Front and rear end separation, yes ajax Technology implementation, the page does not refresh, ajax The request only responds to data, but it still requires a lot of data html To map different url
 In the single page application stage, the front-end route is added on the basis of the separation of the front and rear ends, that is, only one route is required html,Different url Display different component contents, and url Switching does not require a separate request for static resources;
  1. Public ip and Intranet ip. Public ip is the only ip in the Internet and the identification of internet addressing. Intranet ip is the only ip in the LAN and the identification of LAN addressing. Intranet ip addressing finds the corresponding networking equipment according to the routing table, which is the corresponding relationship between ip and mac address;
Intranet ip Range:
  1. There are two ways to modify the url in the browser without refreshing the page (no resource request). One is to use location.hash to modify the url instead of location.href, and the other is to use history.pushState/replaceState (you can click the back button / you can't click the back button) and history.back/go/forward methods in html5 to modify the url;
The difference between the two methods is location.hash Will be url Add in /#/, but history.pushState does not;
history.hash = 'home'
history.pushState({}, '', 'home') // Push url into stack
history.back() // Realize the function of the back button
history.go(-x) // X means x values pop up from the stack
history.forward() // Equivalent to history.go(1)
  1. The Vue router front-end routing plug-in monitors url changes, then finds the corresponding components from the url components mapping, and renders them in the page. For the use of router, first install NPM, and then create src/router/index.js file. Configure the routes mapping relationship in the file, construct VueRouter objects, and use Vue.use(VueRouter) Finally, export the constructed router object and mount it in the Vue instance;
npm install vue-router --save
	// router/index.js will be found by default
	import router from './router'
	new Vue({
	  el: '#app',
	  render: h => h(App)
	Vue.use(Router) // Internally, the vueroter.install method is executed
	export default new Router({
	  routes: [
  1. Configure the route mapping relationship and the mapping relationship between url and component. First, create the home.vue/about.vue component in src/components directory, and add the mapping relationship routes (path component) in route / index.js Finally, add router link and router view labels in App.vue, where router link configures the button to change the url, and router view configures the location of the component to be displayed, which will display the placeholder of the component;
router-link and router-view yes vue router Built in global components, router-link Implement links and change url(location perhaps history Mode)
	export default new Router({
	  routes: [{
	      path: '/home',
	      component: Home
	      path: '/about',
	      component: About
	<router-link to="/home">home page</router-link>
    <router-link to="/about">about</router-link>
  1. Configure the route of the home page. Add the default route with path of / in route / index.js. You can use component or redirect to specify components. Using component, the url will not change when entering the home page. If redirect is used, the home page will be redirected to / home, so as to maintain the consistency between the component and url path;
const routes = [{
		path: '/'
		redirect: /home
  1. The routing modes include hash and history, that is, use location.hash or history.pushState to change the url. The default is hash mode. This mode will add / # / path to the url. If you want to change, configure it when creating vueRouter object;
const router = new VueRouter{
	mode: 'history'
  1. For the route link component, in addition to specifying the attribute to, you can also specify the attributes tag, replace and active class;
attribute to,appoint router-link Click to modify url
 attribute tag,appoint router-link Replaced html Label, default is a Label, can be changed to button,li Such label
 attribute replace,appoint history In mode, use history.replace To change url,The default is history.pushState,The difference is whether the back button fails
 attribute active-class,Represents the current url of router-link Will be added class Value, the default is route-link-active,Commonly used to implement css effect
<router-link tag = "button" to = "/home" replace active-class = "active-router">home page<router-link>
// linkActiveClass can uniformly configure the active class of router link to avoid adding it separately in each router link
const router = new VueRouter{
	linkActiveClass: 'active-router'
  1. Change the routing url through the code, using this r o u t e r . p u s h ( ′ / h o m e ′ ) , or person t h i s . router.push('/home'), or this router.push('/ home') or this.router.replace('/ home') to modify it. One is added to all components in the application in the router source code r o u t e r genus nature , place with can through too t h i s . router attribute, so you can use this Router attribute, so it can be referenced to the routing object through this.router to switch;

Dynamic routing and parameter passing

  1. Dynamic routing, that is, there are variable parameters in the routing url address. For example, the routing url is / user/:userId, there is a userId parameter in the url, and the userId parameter needs to be obtained in the User component;
When you first configure a routing map, the path Designated as /user/:userId
	path: '/user/:userId',
	component: User
Then configure the route jump router-link When, to Splicing in attribute values userId Parameters from data Property. Pay attention to the of the component data It is required to be a function and use v-bind To bind attribute values;
<router-link :to="'/user/'+ userId">user</router-link>
    return {
      userId: 'dengh'
Finally, after route jump User Component, through this.$route.params.userId To get url Parameters;
  1. cli2 packaged dist folder has index.html + js directory + css directory. uglifyJsplugin in webpack.prod.conf.js can be shielded to display uncompressed packaged files;
dist/js Medium:
	app.xxx.js: Applied js
	manifest.xxx.js: Bottom layer of package js Support (e.g commonjs, es6 Modular support)
	vendor.xxx.js: Third party js(vue,vue-router,axios Etc.)
In manual webpack in bundle.js It is through closures and passes in dependencies js Module to realize modularization;
  1. Lazy loading: if the application js (app.xxx.js) is too large and takes a long time to load at one time, it needs to be separated and split according to the route. When the route is accessed, the js required by the corresponding component can be loaded. In implementation, only the introduction method of the component needs to be changed. In this way, the js file of each route component will be added to the packaged js directory, and it can be requested only when the route is active;
use const Home = () => import('../components/Home') replace import Home from '../components/home'
const routes = [
	path: '/home',
	component: Home
  1. For nested routing, first, the matching of routes is the exact matching of URLs. If a route is established in the home component, such as / home/news and / home/message, you need to add the children attribute in the / home route map, use router link + router view in the home component, and configure the default path for embedded routes;
// src/router/index.js
const routes = [{
  path: '/home',
  component: Home,
  children: [{
      path: '/',
      redirect: 'news'
      path: 'news',
      component: HomeNews
      path: 'messages',
      component: HomeMessages
// Home.vue
<router-link to = "/home/news">Journalism</router-link>
<router-link to = "/home/messages">news</router-link>
  1. There are two ways to transfer routing parameters. The url is defined as / router/:id, or / router?k=v. within the routing component, it is passed through this r o u t e . p a r a m s . i d , or person t h i s . route.params.id, or this route.params.id, or this.route.query.key. This. $route.push ({path: XXX, query: {XXX}}) is used when js code performs route jump;
<router-link :to = "{path: '/profile',query:{name:'dengh',age:31}">my</router-link>
this.$router.push({path: '/profile',query:{name:'dengh',age:31})
  1. $router and $route. When executing Vue.use(Router) in router/index.js, the vueroter.install method will be executed internally. In this method, the router link and router view components will be registered globally, and two global attributes $router and $route will be defined for Vue.prototype. The former points to the created vueroouter object, and the latter points to the currently active routing object, Because all Vue components inherit Vue.prototype, they can be used directly inside any component;

Navigation guard

  1. The navigation guard monitors route jumps. The router object has hook functions beforeEach and afterEach, which will call back before and after route jumps respectively;

  2. The parameters of beforeEach are the arrow function of (to, from, next) = > {...}. To and from are the route objects before and after route jump, and must call next() to complete route jump. Next can also pass in parameters, pass in false to prevent route jump, pass in path, change route by url jump, etc. the parameters of afterEach are (to, from) = > {...};

Requirement: when the route changes, the page title The corresponding changes require adding metadata to each route meta-title,Then in beforeEach Medium modification document.title;
// src/router/index.js, matched[0] is to obtain metadata for nested routes. Matched is all components matching routes, and [0] in nested routes is the parent component
router.beforeEach((to, from, next) => {
  document.title = to.matched[0].meta.title;
const router = new Router({
  routes: [
      path: '/profile',
      component: Profile,
      meta: {
        title: 'personal information'
  1. All the above definitions are global guards, which means that they are effective for all routes. There are also guards (beforeEnter) exclusive to routes, which are effective only for a single route, and guards (beforeRouterEnter) in components, which are effective only for a single component;
const router = new Router({
  routes: [
      path: '/profile',
      component: Profile,
      beforeEnter: (to, from, next){
  1. During route switching, previous components are destroyed and new components are created. Keep alive is a built-in component of vue, which can keep the components in the state and will not be re created during the next switching. The use method is to surround the components to be cached with the keep alive tag, At this time, the surrounded components will have activated and deactivated life cycle callbacks, and the components not surrounded by keep alive do not have these two life cycles;
// For the user component, when the router view is not included in keep alive, every time you switch to / user, you will call back created, switch to other URLs, and call destroy
export default {
    name: "User",
    created() {
      console.log("user created");
    destroyed() {
      console.log('user destroy');
// If you include a router view with keep alive, only one created will be called. After that, no matter how the route is switched, created and destroyed will not be called
// Keep alive includes router view. After that, activated and deactivated will be called every time the / user route is switched
export default {
    name: "User",
    activated() {
      console.log("user is  activated")
    deactivated() {
      console.log("user is deactivated")
  1. If the requirement is to switch routes, when switching back, you should maintain the previous state of the routing component, such as the selection of nested routes. At this time, you can first include the router view with keep alive, and record the nested route url when leaving when navigating the guard beforeRouterLeave in the component: this r o u t e . p a t h , most after stay a c t i v a t e d living life week stage in send use t h i s . route.path, and finally use this. Path in the activated lifecycle route.path. Finally, use this. Route. Push (path) in the activated life cycle to switch to the previous nested route url;
Be careful not to deactivated Save in callback this.$route.path,Because when the callback is executed, this.$route.path Has pointed to the next route url
  1. Keep alive also has include and exclude attributes to specify the name of the component to be included or excluded;
// In this way, the created and destroyed of the profile component will be called all the time during route switching
<keep-alive exclude='Profile'><router-vivew /></keep-alive>

Keywords: Front-end Vue.js Webpack

Added by plasmahba on Fri, 12 Nov 2021 06:30:21 +0200