Vue2 scaffolding notes (for personal use)

Vue2 Scaffolding Notes

Initialize scaffolding

3.1.1

illustrate

\1. Vue scaffolding is a standardized development tool (development platform) officially provided by Vue.

\2. The latest version is 4.x.

\3. Documentation: Vue CLI .

3.1.2 Specific steps

Remark:

\1. If the download is slow, please configure the npm Taobao mirror: npm config set registry

https://registry.npm.taobao.org

The first step (only the first execution): install @vue/cli globally.

npm install -g @vue/cli

Step 2: Switch to the directory where you want to create the project , and then use the command to create the project

vue create xxxx

Step 3: Start the project

npm run serve

\2. Vue scaffolding hides all webpack-related configurations. If you want to view specific webpakc configurations,

Please execute: vue inspect > output.js

Scaffolding file structure:

├── node_modules

├── public

│ ├── favicon.ico: tab icon

│ └── index.html: main page

├── src

│ ├── assets: store static resources

│ │ └── logo.png

│ │── component: storage component

│ │ └── HelloWorld.vue

│ │── App.vue: Summarize all components

│ │── main.js: entry file

├── .gitignore: configuration ignored by git version control

├── babel.config.js: babel configuration file

├── package.json: application package configuration file

├── README.md: application description file

├── package-lock.json: package version control file

Regarding different versions of Vue:

1. The difference between vue.js and vue.runtime.xxx.js:

     (1).vue.js is a full version of Vue, including: core functions + template parser

(2).vue.runtime.xxx.js is just the running version of Vue, which only includes: core functions: no template parser.

2. Because vue.runtime.xxx.js does not have a template parser, the template configuration item cannot be used. You need to use the render function to receive the createElement function to specify the specific content.

vue.config.js configuration file

Use vue inspect n> output.js to view the default configuration of Vue scaffolding

Scaffolding can be customized using vue.config.js, see: Vue CLI for details .

ref attribute

1. It is used to register and reference real information for elements or subcomponents (replacement of id)

2. What the application gets on the html tag is the real DOM element, and what the application gets on the component tag is the component instance object (vc)

3. How to use:

Mark: <h1 ref="xxx">......</h1> or <School ref="xxx"></School>

Get: this.$refs.xxx

configuration item props

Function: Let the component accept external data

(1). Transfer data: ​ <Demo name="xxx"/> ​ (2). Receive data:

The first way (receive only): prpos:['name']

The second way (restriction type): ​ props:{ ​ name:Number ​ }

The third way (limit type, limit necessity, specify default value): ​ props:{ ​ name:{ ​ type:String, //type required:true, //necessity default:'Old Wang' / /default value​ } }

  Remarks: props are read-only. The bottom layer of Vue will monitor your modifications to props. If you modify props, a warning will be issued. If the business needs really need to be modified, please copy the content of props to a copy of data, and then modify data data in .

mixin

Function: The configuration shared by multiple components can be extracted into a mix-in object

How to use:

 第一步定义混合,例如:
        {
          data(){.......}
          methods:{......}
           .......
         }
 ​
   第二步使用混入,例如:

(1). Global mix-in: Vue.mixin(xxx)

(2). Partial mix-in: mixins['xxx']

plug-in

Function: Used to enhance Veu

Essence: An object containing the install method, the first parameter of install is Vue, and the second and subsequent parameters are the data passed by the plug-in user.

Define the plugin:

 对象.install = function(Vue,ootions)P{
 ​
   //1.添加全局过滤器
   Vue.filter(......)
 ​
  //2.添加全局指令
     Vue.directive(.....)

//3. Cooperate with global mixin (combination) Vue.mixmin(.....)

//4. Add instance method Vue.prototype.myMethod = function () {.....} Vue.prototype.myProperty = xxx }

Using plugins: Vue.use()

scoped style

Function: Let the style take effect locally to prevent conflicts.

Writing: <style scoped>

Summarize the TodoList case

1. Component coding process:

  (1). Split static components: components should be split according to function points, and the naming should not conflict with html elements.
 ​
 (2). Realize dynamic components: consider where the data is stored, whether the data is used by a component or some components:

1). A component is in use: just put it in the component itself.

  2). Some components are in use: put them on their common parent component (<span style="color:red">state promotion</span>).
 ​
  (3). Realize interaction: start from binding events.

2. props apply to:

(1). Parent component ===> child component communication

(2). Child component ===> parent component communication (requiring the parent to give the child a function first)

3. When using v-model, remember: the value bound by v-model cannot be the value passed by props, because props cannot be modified!

4. If the value passed by props is an object type, Vue will not report an error when modifying the properties in the object, but this is not recommended.

webStorage (local storage)

1. The storage content generally supports about 5MB (different browsers may not be the same)

2. The browser implements the local storage mechanism through the Window.sessionStorage and Window.localStorage properties.

3. Related APIs:

1. xxxxxStorage.setItem('key','value');This method accepts a key and a value as parameters, adds the key-value pair to the storage, and updates its corresponding value if the key name exists.

2.xxxxxStorage.getItem('person');​ This method accepts a key name as a parameter and returns the value corresponding to the key name.

3.xxxxxStorage.removeItem('key');​ This method accepts a key name as a parameter and deletes the key name from storage.

4.xxxxxStorage.clear()​ This method will clear all data in the storage

4. Remarks:

1. The content stored in SessionStorage will disappear with the closing of the browser window.

2. The content stored in LocalStorage needs to be manually cleared before it disappears.

3. xxxxxStoragee.getItem(xxx)If the value corresponding to xxx cannot be obtained, the return value of getItem is null.

4. JSON.parse(null)The result is still null.

JSON.stringify()Used to convert a JavaScript object to a JSON string JSON.parse()Used to convert a JSON string to an object

Component custom events

1. A way of communication between components, suitable for: child components ===> parent components

2. Usage scenario: A is the parent component, B is the child component, and B wants to pass data to A, then it must set a custom event for B in A (event callback is in A)

  1. Bind custom events:

    1. The first way, in the parent component: <Demo @atguigu="test"/>or<Demo v-on atguigu="test"/>

    2. The second way, in the parent component:

     <Demo ref="demo"/>
     ......
     mounted(){
         this.$refs.xxx.$on('atguigu',test)
     }

    3. If you want a custom event to be triggered only once, you can use oncemodifiers, or $oncemethods

4. Trigger a custom event:this.$emit('atgugui',数据)

5. Unbind custom events:this.$off('atgugui')

6. Native DOM events can also be bound to components, which require the use of nativemodifiers

7. Note: this.$refs.student.$on('atguigu',回调)When binding a custom event through ah, the callback must be configured in methods or use an arrow function, otherwise this will cause problems!

Global Event Bus (GlobalEventBus)

1. A way of communication between components, suitable for any communication between components.

2. Install the global event bus:

new Vue({
	......
	beforeCreate(){
		Vue.prototype.$bus = this	//安装全局事件总线,$bus就是当前应用的vm
	},
	......
})

3. Use the event bus:

1. Receive data: If A component wants to receive data, it binds a custom event to $bus in A component, and the callback of the event is left in A component itself.

methods(){
	demo(data){......}
}
......
mounted(){
	this.$bus.$on('xxxx',this.demo)
}

2. Provide data:this.$bus.$emit('xxxx',数据)

4. It is best to use $off in the beforeDestroy hook to unbind the events used by the current component.

Message Subscription and Publishing (pubsub)

1. A communication between components, suitable for any communication between components

2. Steps to use:

1. Install pubsub:npm i pubsub-js

2. Introduce:import pubsub from 'pubsub-js'

3. Receive data: If component A wants to receive data, it subscribes to the message in component A, and the subscribed callback stays in component A itself.

methods(){
demo(data){......}
}
......
mounted(){
	this.pid = pubsub.subscribe('xxx',this.demo)	//订阅消息
}

4. Provide data:pubsub.publist('xxx',数据)

5. It is best PubSub.unsubscribe(pid)to .

nextTick

1. Grammar:this.$nextTick(回调函数)

2. Function: Execute the specified callback after the next DOM update ends

3. When to use: When the data is changed and some operations are to be performed based on the updated DOM, it must be executed in the callback function specified by nextTick.

Transition and animation of Vue package

1. Homework: When inserting, updating or removing DOM elements, add style class names to elements at the appropriate time.

2. Icon:

3. Writing method:

1. Prepare the style:

▪ Elements come in styles:

1. v-enter: the starting point of entry

2. v-enter-active: in the process of entering

3. v-enter-to: Enter the end point​ ▪ The style of the element leaving:

1. v-leave: the starting point of leaving

2. v-leave-active: in the process of leaving

3. v-leave-to: leave the end

2. Use <transition>the element to be wrapped and configure the name attribute:

<transition name="hello">
		<h1 v-show="isShow">你好啊!</h1>
	</transition>

3. Remarks: If there are multiple elements that need to be transitioned, you need to use: <transition-group>, and each element must specify keya value

Vue scaffolding configuration proxy

method one

Add the following configuration in vue.config.js:

devServer:{
	proxy:"http://localhost:5000"
}

illustrate:

1. Advantages: The configuration is simple, and it can be directly sent to the front end (8080) when requesting resources.

2. Disadvantages: Multiple proxies cannot be configured, and it is not possible to flexibly control whether requests go through proxies.

3. Working method: According to the above configuration, when a resource that does not exist in the front-end is requested, the request will be forwarded to the server (matching front-end resources first)

Method Two

Configure specific proxy rules in vue.config.js:

module.exports = {
  devServer: {
    proxy: {
      '/api': {	//匹配所有以'/api'开头的请求路径
        target: 'http://localhost:5000',//代理目标的基础路径
        ws: true,
        changeOrigin: true,
        pathRewrite:{'^/api':''},
      },
      '/api2': {	//匹配所有以'/foo'开头的请求路径
        target: 'http://localhost:5001'//代理目标的基础路径
        pathRewrite:{'^/api2':''},
      }
    }
  }
}
/*
	changeOrigin设置为true时,服务器收到请求头中的host为:localhost:5000
	changeOrigin设置为false时,服务器收到请求头中的host为:localhost:8080
	changeOrigin默认值为true
*/

illustrate:

1. Advantages: Multiple proxies can be configured, and it is possible to flexibly control whether requests go through proxies.

2. Disadvantages: The configuration is slightly cumbersome, and a prefix must be added when requesting resources.

slot

1. Function: Let the parent component insert the html structure to the specified position of the child component, which is also a communication method between components, applicable to parent components ===> child components .

2. Classification: default slots, named slots, scoped slots

3. How to use:

1. Default slot:

父组件中:
	<Category>
		<div>html结构</div>
	</Category>
子组件中:
	<template>
 	 <div>
 	 	<!-- 定义插槽 -->
 	 	<slot>默认插槽内容...</slot>
 	 </div>
 	</template>

2. Named slots:

父组件中:
	<Category>
		<template slot="center">
			<div>html结构</div>
		</template>
		
		<template v-slot="footer">
			<div>html结构2</div>
		</template>
	</Category>
子组件中:
	<template>
 	 <div>
 	 	<!-- 定义插槽 -->
 	 	<slot name="center">默认插槽内容...</slot>
 	 	<slot name="footer">默认插槽内容...</slot>
 	 </div>
 	</template>

3. Act on the slot:

1. Understanding: The data is in the component itself, but the structure generated according to the data needs to be determined by the user of the component . (The games data is in the Category component, but the structure traversed by using the data is determined by the App component)

2. Specific coding:

父组件中:
	<Category>
      <template scope="scopeData">
      	<!-- 生成的是ul列表 -->
        <ul>
          <li v-for="(g,index) in scopeData.games" :key="index">{
   
   {g}}</li>
        </ul>
      </template>
    </Category>
    
     <Category>
      <template slot-scope="{scopeData">
        <h4 v-for="(g,index) in scopeData.games" :key="index">{
   
   {g}}</h4>
      </template>
    </Category>
子组件中:
	<template>
 	 <div >
      <slot :games="games"></slot>
 	 </div>
	</template>
	
	<script>
    export default {
        name:'Category',
        props:['title'],
        data(){
            return{
             games:['王者荣耀','和平精英','刺激战场','原神','推箱子'],
            }
      }
    }
</script>

Vuex

 

1. Concept

A Vue plug-in that implements centralized state (data) management in Vue, and performs centralized management (read/write) on the shared state of multiple components in the Vue application. It is also a way of communication between components, and it is suitable for any Communication between components.

2. When to use it?

When multiple components need to share data

3. Build the vuex environment

1. Create a file:src/store/index.js

// 该文件用于创建Vuex中最为核心的store

// 引入Vue
import Vue from 'vue'
// 引入Vuex
import Vuex from 'vuex'
// 应用Vuex的插件
Vue.use(Vuex)

// 准备actions——用于响应组件中的动作
const actions = {}
// 准备mutations——用于操作数据(state)
const mutations = {}
// 准备state——用于存储数据
const state = {}

// 创建并导出/暴露store
export default new Vuex.Store({
    actions,
    mutations,
    state,
})

2. Pass in configuration items main.jswhen creating a vm instore

......
// 引入store
import store from './store'
......

// 创建vm
new Vue({
  el:'#app',
  render: h => h(App),
  store
})

4. Basic use

1. Initialize data, configure actions, configure mutations, and operate filesstore.js

// 该文件用于创建Vuex中最为核心的store

// 引入Vue
import Vue from 'vue'
// 引入Vuex
import Vuex from 'vuex'
// 应用Vuex的插件
Vue.use(Vuex)

// 准备actions——用于响应组件中的动作
const actions = {
     jia(context,value){
        console.log('action中的jia被调用了');
        context.commit('JIA',value)
    },
}

// 准备mutations——用于操作数据(state)
const mutations = {
	//	执行加
    JIA(state,value){
        console.log('mutations中的JIA被调用了');
        state.sum += value
    },
}
// 准备state——用于存储数据
const state = {
    sum:0 //当前的和
}

// 创建并导出/暴露store
export default new Vuex.Store({
    actions,
    mutations,
    state,
})

2. Read the data in vuex in the component:$store.state.sum

3. Modify the data in vuex in the component: $store.dispatch('action中的方法名',数据)or$store.commit('mutations中的方法名',数据)

Remarks: If there is no network request or other business logic, actions can also be surpassed in the component, that is, do not write dispatch, write directlycommit

5. Use of getters

1. Concept: When the data in the state needs to be processed before use, getters can be used for processing.

2. store.jsAppend gettersconfiguration in

......
const getters = {
    bigSum(state){
        return state.sum*10
    }
}
// 创建并导出/暴露store
export default new Vuex.Store({
    ......
    getters,
})

3. Read data in the component:$store.getters.bigSum

6. The use of four map methods

1. mapState method: help us map statethe data into computed properties

computed:{
	// 借助mapState生成计算属性,从state中读取数据。(对象写法)
 ...mapState({he:'sum',xuexiao:'school',xueke:'subject'}),

          // 借助mapState生成计算属性,从state中读取数据。(数组写法)
          ...mapState(['sum','school','school']),
}

2. mapGetter method: help us map gettersthe data into computed properties

computed:{
	// 借助mapGetters生成计算属性,从getters中读取数据。(对象写法)
           ...mapGetters({bigSum:'bigSum'})

          // 借助mapGetters生成计算属性,从getters中读取数据。(数组写法)
          ...mapGetters(['bigSum'])
}

3. mapActions method: the method used to help us generate actionsdialogues, namely: the included $store.dispatch(xxx)functions

methods:{
	// 借助mapActions生成对应的方法,方法中会调用dispatch去联系吗action(对象写法)
          ...mapActions({incrementOdd:'jiaOdd',incrementWait:'jiaWait'})

          // 借助mapActions生成对应的方法,方法中会调用dispatch去联系吗action(数组写法)
           ...mapActions(['jiaOdd','jiaWait'])
}

4. mapMutations method: the method used to help us generate mutationsdialogues, namely: the included $store.commit(xxx)functions

methods:{
	// 借助mapMutations生成对应的方法,方法中会调用commit去联系吗mutations(对象写法)
          ...mapMutations({increment:'JIA',decrement:'JIAN'}),

          // 借助mapMutations生成对应的方法,方法中会调用commit去联系吗mutations(数组写法)
           ...mapMutations(['JIA','JIAN']),
}

Remarks: When using mapActions and mapMutations, if you need to pass parameters: pass the parameters when binding the event in the template, otherwise the parameters are event objects

7. Modularity + Namespace

1. Purpose: To make the code easier to maintain and to make the classification of various data more clear.

2. Modifystore.js

const countAbout = {
	namespaced:true	//开启命名空间
	state:{x:1},
	mutations{...},
	actions:{...},
	getters:{
        bigSum(state){
            return state.sum*10
        }
    }
}

const personAbout = {
	namespaced:true	//开启命名空间
	state:{x:1},
	mutations{...},
	actions:{...},
}

const store = new Vuex.Store({
    modules:{
        constAbout:constOptions,
        personAbout:personOptions
    }
})

3. After enabling the namespace, read the state data in the component:

//方式一:自己直接读取
this.$store.state.personAbout.list
//方式二:借助mapState读取
...mapState('constAbout',['sum','school','subject']),

4. After enabling the namespace, read the getters data in the component:

//方式一:自己直接读取
this.$store.getters['personAbout/firstPersonName']
//方式二:借助mapGetters读取
...mapGetters('constAbout',['bigSum'])

5. After the namespace is enabled, dispatch is called in the component

//方式一:自己直接dispatch
this.$store.dispatch('personAbout/addPersonWang',personObj)
//方式二:借助mapActions读取
...mapActions('constAbout',{incrementOdd:'jiaOdd',incrementWait:'jiaWait'})

6. After the namespace is enabled, commit is called in the component

//方式一:自己直接commit
this.$store.commit('personAbout/ADD_PERSON',personObj)
//方式二:借助mapMutations读取
...mapMutations('constAbout',{increment:'JIA',decrement:'JIAN'}),

routing

1. Understanding: A route (router) is a set of mapping relationships (key-value), and multiple routes need a router (router) to manage.

2. Front-end use: key is the path, and value is the component.

1. Basic use

1. Install vue-router, command:npm i vue-router

2. Application plugin:Vue.use(VueRouter)

3. Write router configuration items:

// 引入VueRouter
import VueRouter from "vue-router";
// 引入luyou组件
import About from '../components/About'
import Home from '../components/Home'

// 创建router实例对象,去管理一组一组的路由规则
const router = new VueRouter({
    routes:[
        {
            path:'/about',
            component:About
        },
        {
            path:'/home',
            component:Home
        }
    ]
})

//	暴露router
export default router

4. Realize switching (active-class can configure highlighting style)

<router-link class="list-group-item" active-class="active" to="/about">About</router-link>

5. Designate placements

<router-view></router-view>

2. A few points for attention

1. Routing components are usually stored in pagesfolders, and general components are usually stored in componentsfolders.

2. By switching, the "hidden" routing components are destroyed by default, and then mounted when needed.

3. Each component has its own $routerproperties, which store its own routing information.

4. There is only one router in the whole application, which can $routerbe obtained through the properties of the component.

3. Multi-level routing (multi-level routing)

1. Configure routing rules, using the children configuration item:

routes:[
        {
            path:'/about',
            component:About
        },
        {
            path:'/home',
            component:Home,
            children:[	//通过children配置子级路由
                {
                    path:'news',	//此处一定不要写:/news
                    component:News,
                },
                {
                    path:'message',	//此处一定不要写:/message
                    component:Message,
                }
            ]
        }
    ]

2. Jump (to write the full path):

<router-link class="list-group-item" active-class="active" to="/home/news">News</router-link>

4. The query parameter of the route

1. Pass parameters

<!-- 跳转路由并携带query参数,to的字符串写法 -->
<router-link :to="/home/message/detail?id=666&title=你好啊!">跳转</router-link>

<!-- 跳转路由并携带query参数,to的对象写法 -->
<router-link :to="{
       path:'/home/message/detail',
       query:{
           id:m.id,
           title:m.title,
       }
  }"
>跳转</router-link>

2. Receive parameters:

$route.query.id
$route.query.title

5. Naming Routes

1. Function: It can simplify the routing jump.

2. How to use

1. Name the route:

{
      path:'/demo',
      component:Demo,
      children:[
          {
              path:'test',
              component:Test,
              children:[
                  {
                      name:'hello',	//给路由命名
                      path:'welcome',
                      component:Hello,
                   }
               ]
          }
      ]
}

2. Simplify the jump:

<!-- 简化前:需要写完整的路径 -->
<router-link to='/demo/test/welcome'>跳转</router-link> 

<!-- 简化后:直接通过名字跳转 -->
<router-link :to="{name:'hello'}">跳转</router-link> 

<!-- 简化写法配合传递参数 -->
<router-link 
	:to="{
        name:'xiangqing',
        query:{
           id:666,
           title:'你好',
         }
    }"
>跳转</router-link>

6. Paramscans for routing

1. Configure routing and declare to receive params parameters

{
	path:'/home',
    component:Home,
    children:[
    	{
    		path:'news',
    		component:News,
    	},
    	{
   		 path:'message',
   		 component:Message,
   		 children:[
   			 {
    			name:'xiangqing',
    			path:'detail/:id/:title',	//使用占位符声明接收params参数
   				component:Detail,
  			 }
    	   ]
   		}
    ]
  }

2. Pass parameters

<!-- 跳转路由并携带params参数,to的字符串写法 -->
<router-link :to="/home/message/detail/666/你好啊!">跳转</router-link>

<!-- 跳转路由并携带params参数,to的对象写法 -->
<router-link 
	:to="{
		name:'xiangqing',
		params:{
			id:666,
			title:你好,
		}
	}"
>跳转</router-link>

Special attention: When the route carries params parameters, if you use the object writing method of to, you cannot use the path configuration item, it must be the name configuration!

3. Receive parameters:

$route.params.id
$route.params.title

7. Routing props configuration

Role: Make it easier for routing components to receive parameters

{
	name:'xiangqing'
	path:'detail/:id',
	component:Detail,
	// 第一种写法,props的值为对象,该对象中的所有key-value都会以props的形式传给Detail组件
    // props:{a:1,b:'hello'}

	// 第二种写法,props的值为布尔值,若布尔值为true,则把路由组件收到的所有params参数通过props传给Detail组件
    // props:true

    // 第三种写法,props的值为函数,该函数返回的对象中每一组key-value都会通过props传递给Detail组件
    	props($route){
   		 return {
    		id:$route.query.id,
   			 title:$route.query.title
    		}
    // 第三种简写形式:
    /*props({query:{id,title}}){
    	return {id,title}
   	 } */
   	     }
	}
}

8. <router-link>The replace attribute

1. Function: Control the mode of operating browser history records when routing jumps

2. There are two ways to write the history of the browser: and respectively push, replacewhich pushis to append the history record, and replaceis to replace the current record. When the route jumps, the default ispush

3. How to open replacethe mode:<router-link replace ......>News<router-link>

9. Programmatic Routing Navigation

1. Function: <router-link>Make routing jump more flexible without the help of routing jump

2. Specific coding:

//$router的两个API
this.$router.push({
	name:'xiangqing',
		params:{
			id:xxx,
			title:xxx,
		}
})

this.$router.replace({
	name:'xiangqing',
		params:{
			id:xxx,
			title:xxx,
		}
})
this.$router.back()	//前进
this.$router.forward()	//后退
this.$router.go()	//可前进也可后退

10. Cache Routing Components

1. Function: Keep the routing components that are not displayed to be mounted and not destroyed.

2. Specific coding:

<keep-alive include="NewsX">
   <router-view></router-view>
</keep-alive>

11. Two new lifecycle hooks

1. Function: Two hooks unique to the routing component, used to capture the activation status of the routing component.

2. Specific name:

1. activatedTriggered when the routing component is activated.

2. deactivatedTriggered when the routing component is deactivated.

12. Route Guard

1. Role: to control the authority of the route

2. Classification: global guard, exclusive guard, component guard

3. Global guard:

// 全局前置路由守卫————初始化的时候被调用、每次路由切换之前被调用
router.beforeEach((to,from,next)=>{
    console.log('前置路由守卫',to,from);
    if(to.meta.isAuth){ //判断当前路由是否需要权限配置
        if(localStorage.getItem('school')==='atguigu'){	//权限控制的具体规则
            next()	//放行
        }else{
            alert("学校名不对,无权限查看!")
            //	next({name:'guanyu'})
        }
    }else{
        next()	//放行
    }
})

// 全局后置路由守卫————初始化的时候被调用、每次路由切换之后被调用
router.afterEach((to,from)=>{
    console.log('后置路由守卫',to,from);
     if(to.meta.title){
     	document.title = to.meta.title || '宋一鲤'	//修改网页的title
     }else{
     	document.title = 'vue_test
     }
})

4. Exclusive guard:

beforeEnter:(to,from,next) => {
	console.log('beforeEnter',to,from);
	if(to.meta.isAuth){ //判断当前路由是否需要进行权限控制
		if(localStorage.getItem('school')==='atguigu'){
			next()
		}else{
			alert("暂无权限查看")
			//	next({name:'guanyu'})
		}
		}else{
			next()
		}
}

5. Guard within the component:

// 进入守卫:通过路由规则,进入该组件时被调用
beforeRouteEnter(to,from,next){
},
// 离开守卫:通过路由规则,离开该组件时被调用
beforeRouteLeave(to,from,next){
}

13. Two working modes of the router

1. For a url, what is the hash value? ——# and the content after it is the hash value.

2. The hash value will not be included in the HTTP request, that is: the hash value will not be brought to the server.

3. Hash mode:

1. There is always a # sign in the address, which is not beautiful.

2. If the address is shared through a third-party mobile app in the future, if the app checks strictly, the address will be marked as illegal.

3. Good compatibility.

4. History mode:

1. The address is clean and beautiful.

2. Compatibility is slightly worse than hash mode.

3. When the application is deployed online, it needs the support of the back-end personnel to solve the problem of refreshing the page server 404.

Guess you like

Origin blog.csdn.net/m0_62068678/article/details/126822528