Learning vue2 notes

Learning vue2 notes

Scaffolding file structure

├── node_modules 
├── public
│   ├── favicon.ico: 页签图标
│   └── index.html: 主页面
├── src
│   ├── assets: 存放静态资源
│   │   └── logo.png
│   │── component: 存放组件
│   │   └── HelloWorld.vue
│   │── App.vue: 汇总所有组件
│   │── main.js: 入口文件
├── .gitignore: git版本管制忽略的配置
├── babel.config.js: babel的配置文件
├── package.json: 应用包配置文件 
├── README.md: 应用描述文件
├── package-lock.json:包版本控制文件

About 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 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, and the createElement function received by the render function needs to be used to specify the specific content.

vue.config.js configuration file

  1. Use vue inspect > output.js to view the default configuration of Vue scaffolding.
  2. Scaffolding can be customized using vue.config.js. For details, see: https://cli.vuejs.org/zh

ref attribute

  1. Used to register reference 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:
    1. Mark: <h1 ref="xxx">.....</h1>or<School ref="xxx"></School>
    2. Obtain:this.$refs.xxx

props configuration item

  1. Function: Let the component receive data from the outside

  2. Pass data:<Demo name="xxx"/>

  3. Receive data:

    1. The first way (receive only):props:['name']

    2. Second way (restricted type):props:{name:String}

    3. Third way (restrict type, restrict necessity, specify default value):

      props:{
              
              
      	name:{
              
              
      	type:String, //类型
      	required:true, //必要性
      	default:'老王' //默认值
      	}
      }
      

    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 contents of props to a copy of data, and then modify the data in data.

mixin

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

  2. How to use:

    The first step is to define the mixin:

    {
        data(){....},
        methods:{....}
        ....
    }
    

    The second step uses mixins:

    ​ Global mix-in: Vue.mixin(xxx)
    Local mix-in:mixins:['xxx']

plug-in

  1. Function: used to enhance Vue

  2. 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.

  3. Define the plugin:

    对象.install = function (Vue, options) {
          
          
        // 1. 添加全局过滤器
        Vue.filter(....)
    
        // 2. 添加全局指令
        Vue.directive(....)
    
        // 3. 配置全局混入(合)
        Vue.mixin(....)
    
        // 4. 添加实例方法
        Vue.prototype.$myMethod = function () {
          
          ...}
        Vue.prototype.$myProperty = xxxx
    }
    
  4. Use the plugin:Vue.use()

scoped style

  1. Function: Let the style take effect locally to prevent conflicts.
  2. 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 the storage location of the data, 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 (state promotion).

    ​ (3). Realize interaction: start from binding events.

  2. props apply to:

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

    ​ (2). Child component ==> parent component communication (requires 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

  1. The storage content size generally supports about 5MB (different browsers may vary)

  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, and will add the key-value pair to the storage, and if the key exists, update its corresponding value.

    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 the storage.

    4. xxxxxStorage.clear()

      ​ This method clears all data in the storage.

  4. Remark:

    1. The content stored in SessionStorage will disappear when the browser window is closed.
    2. The content stored in LocalStorage needs to be manually cleared before it disappears.
    3. xxxxxStorage.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.

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 needs to bind a custom event to B in A (event callback is in A).

  3. 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',this.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('atguigu',数据)

  5. Unbind custom eventsthis.$off('atguigu')

  6. Components can also be bound to native DOM events, requiring the use of nativemodifiers.

  7. Note: When this.$refs.xxx.$on('atguigu',回调)binding a custom event, the callback must either 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. Using the event bus:

    1. Receive data: If component A wants to receive data, then bind a custom event to $bus in component A, and the callback of the event stays in component A 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 way of communication between components, suitable for any communication between components.

  2. Steps for usage:

    1. Install pubsub:npm i pubsub-js

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

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

      methods(){
              
              
        demo(data){
              
              ......}
      }
      ......
      mounted() {
              
              
        this.pid = pubsub.subscribe('xxx',this.demo) //订阅消息
      }
      
    4. provide data:pubsub.publish('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.
  3. When to use: When the data is changed and some operations are to be performed based on the updated new DOM, it must be executed in the callback function specified by nextTick.

Transition and animation of Vue package

  1. Function: When inserting, updating or removing DOM elements, add a style class name to the element at the appropriate time.

  2. Graphic:

  3. Writing:

    1. Ready to 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: the end point of entry
      • Styles for element leaving:
        1. v-leave: the starting point of leaving
        2. v-leave-active: in the process of leaving
        3. v-leave-to: the end point of leaving
    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 sent directly 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: If the proxy is configured as above, 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

​ Write vue.config.js to configure specific proxy rules:

module.exports = {
    
    
	devServer: {
    
    
      proxy: {
    
    
      '/api1': {
    
    // 匹配所有以 '/api1'开头的请求路径
        target: 'http://localhost:5000',// 代理目标的基础路径
        changeOrigin: true,
        pathRewrite: {
    
    '^/api1': ''}
      },
      '/api2': {
    
    // 匹配所有以 '/api2'开头的请求路径
        target: 'http://localhost:5001',// 代理目标的基础路径
        changeOrigin: true,
        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: Allow the parent component to insert the html structure to the specified position of the child component, and it is also a way of communication between components, which is suitable for parent components ===> child components .

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

  3. How to use:

    1. Default slot:

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

      父组件中:
              <Category>
                  <template slot="center">
                    <div>html结构1</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. Scoped slots:

      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 encoding:

        父组件中:
        		<Category>
        			<template scope="scopeData">
        				<!-- 生成的是ul列表 -->
        				<ul>
        					<li v-for="g in scopeData.games" :key="g">{
                 
                 {g}}</li>
        				</ul>
        			</template>
        		</Category>
        
        		<Category>
        			<template slot-scope="scopeData">
        				<!-- 生成的是h4标题 -->
        				<h4 v-for="g in scopeData.games" :key="g">{
                 
                 {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 a Vue application. It is also a way of communication between components, and 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

    //引入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, manipulate filesstore.js

    //引入Vue核心库
    import Vue from 'vue'
    //引入Vuex
    import Vuex from 'vuex'
    //引用Vuex
    Vue.use(Vuex)
    
    const actions = {
          
          
        //响应组件中加的动作
    	jia(context,value){
          
          
    		// console.log('actions中的jia被调用了',miniStore,value)
    		context.commit('JIA',value)
    	},
    }
    
    const mutations = {
          
          
        //执行加
    	JIA(state,value){
          
          
    		// console.log('mutations中的JIA被调用了',state,value)
    		state.sum += value
    	}
    }
    
    //初始化数据
    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 skipped 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: used to help us map statethe data into computed properties

    computed: {
          
          
        //借助mapState生成计算属性:sum、school、subject(对象写法)
         ...mapState({
          
          sum:'sum',school:'school',subject:'subject'}),
             
        //借助mapState生成计算属性:sum、school、subject(数组写法)
        ...mapState(['sum','school','subject']),
    },
    
  2. mapGetters method: used to help us map gettersthe data into computed properties

    computed: {
          
          
        //借助mapGetters生成计算属性:bigSum(对象写法)
        ...mapGetters({
          
          bigSum:'bigSum'}),
    
        //借助mapGetters生成计算属性:bigSum(数组写法)
        ...mapGetters(['bigSum'])
    },
    
  3. mapActions method: the method used to help us generate and actionsdialogue, namely: the included $store.dispatch(xxx)function

    methods:{
          
          
        //靠mapActions生成:incrementOdd、incrementWait(对象形式)
        ...mapActions({
          
          incrementOdd:'jiaOdd',incrementWait:'jiaWait'})
    
        //靠mapActions生成:incrementOdd、incrementWait(数组形式)
        ...mapActions(['jiaOdd','jiaWait'])
    }
    
  4. mapMutations method: the method used to help us generate and mutationsdialogue, namely: $store.commit(xxx)the function contained

    methods:{
          
          
        //靠mapActions生成:increment、decrement(对象形式)
        ...mapMutations({
          
          increment:'JIA',decrement:'JIAN'}),
        
        //靠mapMutations生成:JIA、JIAN(对象形式)
        ...mapMutations(['JIA','JIAN']),
    }
    

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

7. Modularity + Namespace

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

  2. Revisestore.js

    const countAbout = {
          
          
      namespaced:true,//开启命名空间
      state:{
          
          x:1},
      mutations: {
          
           ... },
      actions: {
          
           ... },
      getters: {
          
          
        bigSum(state){
          
          
           return state.sum * 10
        }
      }
    }
    
    const personAbout = {
          
          
      namespaced:true,//开启命名空间
      state:{
          
           ... },
      mutations: {
          
           ... },
      actions: {
          
           ... }
    }
    
    const store = new Vuex.Store({
          
          
      modules: {
          
          
        countAbout,
        personAbout
      }
    })
    
  3. After the namespace is enabled, the state data is read in the component:

    //方式一:自己直接读取
    this.$store.state.personAbout.list
    //方式二:借助mapState读取:
    ...mapState('countAbout',['sum','school','subject']),
    
  4. After the namespace is enabled, getters data is read in the component:

    //方式一:自己直接读取
    this.$store.getters['personAbout/firstPersonName']
    //方式二:借助mapGetters读取:
    ...mapGetters('countAbout',['bigSum'])
    
  5. After the namespace is enabled, dispatch is called in the component

    //方式一:自己直接dispatch
    this.$store.dispatch('personAbout/addPersonWang',person)
    //方式二:借助mapActions:
    ...mapActions('countAbout',{
          
          incrementOdd:'jiaOdd',incrementWait:'jiaWait'})
    
  6. After the namespace is enabled, commit is called in the component

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

routing

  1. Understanding: A route is a set of mapping relationships (key-value), and multiple routes need to be managed by a router.
  2. Front-end routing: the key is the path, and the value is the component.

1. Basic use

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

  2. Apply 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. Implement switching (active-class can configure highlighting style)

    <router-link active-class="active" to="/about">About</router-link>
    
  5. target 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 $routeproperties, which store its own routing information.
  4. The entire application has only one router, which can $routerbe obtained through the properties of the component.

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

  1. To configure routing rules, use 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 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:666,
                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. Give the route a name:

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

      <!--简化前,需要写完整的路径 -->
      <router-link to="/demo/test/welcome">跳转</router-link>
      
      <!--简化后,直接通过名字跳转 -->
      <router-link :to="{name:'hello'}">跳转</router-link>
      
      <!--简化写法配合传递参数 -->
      <router-link 
      	:to="{
      		name:'hello',
      		query:{
      		   id:666,
                  title:'你好'
      		}
      	}"
      >跳转</router-link>
      

6. The params parameter of the route

  1. Configure routing, declare to receive params parameters

    {
          
          
    	path:'/home',
    	component:Home,
    	children:[
    		{
          
          
    			path:'news',
    			component:News
    		},
    		{
          
          
    			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, you must use 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:900}

	//第二种写法:props值为布尔值,布尔值为true,则把路由收到的所有params参数通过props传给Detail组件
	// props:true
	
	//第三种写法:props值为函数,该函数返回的对象中每一组key-value都会通过props传给Detail组件
	props(route){
    
    
		return {
    
    
			id:route.query.id,
			title:route.query.title
		}
	}
}

8. <router-link>The replace attribute

  1. Role: control the mode of operating browser history when routing jumps
  2. There are two ways to write the history of the browser: pushand respectively replace, pushwhich is to append the history record, and replaceis to replace the current record. When the route jumps, the default ispush
  3. How to turn on replacethe mode:<router-link replace .......>News</router-link>

9. Programmatic Routing Navigation

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

  2. Specific encoding:

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

10. Cache Routing Components

  1. Function: keep the routing components that are not displayed mounted and not destroyed.

  2. Specific encoding:

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

11. Two new lifecycle hooks

  1. Function: Two hooks unique to routing components, used to capture the activation status of routing components.
  2. specific name:
    1. activatedFired 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. Category: global guard, exclusive guard, component guard

  3. Global Guard:

    //全局前置守卫:初始化时执行、每次路由切换前执行
    router.beforeEach((to,from,next)=>{
          
          
    	console.log('beforeEach',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('afterEach',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. Guards inside 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 verification is strict, the address will be marked as illegal.
    3. Compatibility is better.
  4. history mode:

    1. The address is clean and beautiful.
    2. Compatibility is slightly worse than hash mode.
    3. When the application is deployed and launched, 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/AN_NI_112/article/details/131493263