Vue learning notes (self use, incomplete)

Posted by dmschenk on Tue, 08 Mar 2022 01:22:45 +0100

Vue

summary

Is a progressive JavaScript framework for building user interfaces. Vue is designed to be applied layer by layer from the bottom up. Vue's core library only focuses on view layers to facilitate integration with third-party libraries or existing projects.

Soc separation of concerns principle

UI framework

  • Ant design, produced by Alibaba, is a UI framework based on React
  • ElementUI, iview, ice: hungry, Vue based UI framework
  • Bootstrap: an open source toolkit for front-end development launched by twitter
  • AmazeUI: a basket of HTML5 cross screen front-end frame of sister UI

First Vue program

New general project

Install Vue plug-in settings – > plugins

Import Vue js

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello-Vue</title>
</head>
<body>
<div id="app">
    {{message}}
</div>
<!--Import vue.js-->
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.min.js"></script>
<script>
    var vm = new Vue({
        el: "#app",
        data:{
            message: "hello vue"
        }
    });
</script>
</body>
</html>

You can use vm.com after f12 message=“hahahh”

Change the content in div

What is MVVM

MVVM is a software architecture design pattern, which is an event driven programming method to simplify the user interface

From the classic MVC mode. The core of MVVM is the ViewModel layer, which is responsible for transforming the data objects in the Model to make the data easier to manage and use. Its function: bidirectional data binding with the view layer upward and data interaction with the Model layer downward through interface request

Why use MVVM

MVVM mode is the same as MVC mode. Its main purpose is to separate View and Model

  • Low coupling: the View can be changed and modified independently of the Model, and a ViewModel can be bound to different views
  • Reusability: you can put some View logic into a ViewModel, so that many views can reuse this View logic
  • Independent development: developers can focus on the development of business logic and data, and designers can focus on page design
  • Testable

Vue basic syntax

Binding element attributes with v-bind

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello-Vue</title>
</head>
<body>
<div id="app">
    <span v-bind:title="message">
        Hover the mouse for a few seconds to view the prompt information of dynamic binding
    </span>
</div>
<!--Import vue.js-->
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.min.js"></script>
<script>
    var vm = new Vue({
        el: "#app",
        data:{
            message: "hello vue"
        }
    });
</script>
</body>
</html>

v-if v-else

<div id="app">
    <h1 v-if="type==='A'">A</h1>
    <h1 v-else-if="type==='B'">B</h1>
    <h1 v-else>C</h1>
</div>
<!--Import vue.js-->
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.min.js"></script>
<script>
    var vm = new Vue({
        el: "#app",
        data:{
            type: 'A'
        }
    });
</script>

v-for

<div id="app">
    <li v-for="item in items">
        {{item.message}} 
    </li>
</div>
<!--Import vue.js-->
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.min.js"></script>
<script>
    var vm = new Vue({
        el: "#app",
        data:{
            items: [
                {message: 'zhangsan'},
                {message: 'lisi'},
                {message: 'wangwu'}
            ]
        }
    });
</script>

Vue binding events

v-on instruction

<div id="app">
    <button v-on:click="sayHi">Point me</button>
</div>
<!--Import vue.js-->
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.min.js"></script>
<script>
    var vm = new Vue({
        el: "#app",
        data: {},
        methods: {
            sayHi:function(){
                alert("hello")
            }
        }
    });
</script>

Vue bidirectional binding

Data change, view change, view change, data change

Using two-way data binding v-model in form

<div id="app">
 Please enter:<input type="text" v-model="message"> {{message}}<br>

    <input type="radio" value="male" v-model="sex">male
    <input type="radio" value="female" v-model="sex">female<br>
    The selected gender is:{{sex}}


</div>
<!--Import vue.js-->
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.min.js"></script>
<script>
    var vm = new Vue({
        el: "#app",
        data:{
           message: '',
            sex: ''
        }
    });
</script>

Vue components

What is a component: a component is a reusable Vue instance. In other words, it is a set of reusable templates

<div id="app">
<!--    item Is the formal parameter passed item binding -->
    <haha v-for="item in items" v-bind:x="item"></haha>
</div>
<!--Import vue.js-->
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.min.js"></script>
<script>
    // Define a component called haha
    Vue.component('haha',{
        //Receive parameter
        props: ['x'],
        //Contents of components
        template: '<li>{{x}}</li>'
    })
    var vm = new Vue({
        el: "#app",
        data: {
            // Define an array named items
            items: [1,3,4,7,8]},
    });
</script>

Note:

The parameters in the component need to be received and defined by props

You need to bind through v-bind

Axios asynchronous communication

Axios is an open source, which can be used in browser and node JS asynchronous communication framework, the main role is to achieve Ajax asynchronous communication. Main functions:

  • Create XMLHttpRequests from the browser
  • From node JS create http request
  • Support Promise API [chain programming in JS]
  • Intercept requests and responses
  • Convert request data and response data
  • Cancel request
  • Automatically convert JSON data
  • The client supports defense against xsrf (Cross Site Request Forgery)

Life cycle of Vue

Create from start, initialize data, compile template, Mount DOM, render update = render, uninstall

Control can be achieved in the life cycle of vue through hook events

example

First, there is a data JSON file

{
  "name":"Madness theory java",
  "url": "http://baidu.com",
  "page": "1",
  "isNonProfit":"true",
  "address": {
    "street": "Light gate",
    "city":"Xi'an, Shaanxi",
    "country": "China"
  },
  "links": [
    {
      "name": "B station",
      "url": "https://www.bilibili.com/"
    },
    {
      "name": "4399",
      "url": "https://www.4399.com/"
    },
    {
      "name": "Baidu",
      "url": "https://www.baidu.com/"
    }
  ]
}
<body>
<div id="app">
    <div>{{info.name}}</div>
    <div>{{info.address.street}}</div>
</div>


<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script type="text/javascript">
    var vm = new Vue({
        el: '#app',
        //data: Yes attribute
        //data() is a method
        data(){
            return{
                info: {
                    name: null,
                    address:{
                        street: null,
                        city: null,
                        country: null
                    }
                }
            }
        },
        mounted(){//Hook function chain programming
            axios.get('../data.json').then(response=>(this.info=response.data));
        }
    });
</script>
</body>

Calculation properties

What are calculated attributes:

An attribute that can cache the calculation results (convert the behavior into a static attribute) can be imagined as a cache

Case:

<div id="app">
<p>{{currentTime1}}</p>
<p>{{currentTime2}}</p>
</div>


<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.min.js"></script>

<script type="text/javascript">
    var vm = new Vue({
        el: '#app',
        data: {
            message: "haha"
        },
        methods: {
            currentTime1: function(){

                return Date.now();
            }
        },
        computed: {
            currentTime2: function(){
                return Date.now();
            }
        }
    });
</script>

explain:

  • methods defines a method. Calling a method requires parentheses
  • computed: defines the calculated attribute. The calling attribute does not need parentheses

Note: the method names in methods and calculated should not be repeated

slot

Slots are defined with labels and components are bound through the name attribute

Bind data through v-bind

case

<div id="app">
    <todo>
        <todo-title slot="todo-title" v-bind:title="title"></todo-title>
        <todo-items slot="todo-items" v-for="item in todoItems" v-bind:item="item"></todo-items>
    </todo>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.min.js"></script>
<script>
    //Define components
    Vue.component("todo",{
        template: '<div>\
                        <slot name="todo-title"></slot>\
                        <ul>\
                            <slot name="todo-items"></slot>\
                        </ul>\
                   </div>'
    });
    //The components defined in the slot are bound through the name attribute in the slot
    Vue.component("todo-title",{
        props:['title'],
        template:'<div>{{title}}</div>'
    });
    Vue.component("todo-items",{
        props:['item'],
        template:'<li>{{item}}</li>'
    })
    var vm = new Vue({
        el: '#app',
        data:{
            title: "hahaha",
            todoItems: [1,2,3,4]
        }
    })
</script>

Custom components

Case: delete operation completed

Resolution:

The button button in the todo items component is bound with a click event remove

The remove function passes this$ The emit () method binds to the of the front-end interface and passes the parameters

v-on:removes="removeItems(index)

The front end is bound with the function removeItems in the vm, and the parameters are passed

<div id="app">
    <todo>
        <todo-title slot="todo-title" v-bind:title="title"></todo-title>
        <todo-items slot="todo-items" v-for="(item,index) in todoItems"
                    v-bind:item="item" v-bind:index="index"
                    v-on:removes="removeItems(index)"></todo-items>
    </todo>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.min.js"></script>
<script>
    //Define components
    Vue.component("todo",{
        template: '<div>\
                        <slot name="todo-title"></slot>\
                        <ul>\
                            <slot name="todo-items"></slot>\
                        </ul>\
                   </div>'
    });
    //The components defined in the slot are bound through the name attribute in the slot
    Vue.component("todo-title",{
        props:['title'],
        template:'<div>{{title}}</div>'
    });
    Vue.component("todo-items",{
        props:['item','index'],
        template:'<li>{{item}} <button v-on:click="remove">delete</button></li>',
        methods: {
            remove:function(index){
                this.$emit('removes',index);
            }
        }
    })
    var vm = new Vue({
        el: '#app',
        data:{
            title: "hahaha",
            todoItems: [1,2,3,4]
        },
        methods: {
            removeItems: function(index){
                console.log('Subscript deleted'+index+",Element is"+this.todoItems[index]);
                this.todoItems.splice(index,1);
            }
        }
    })
</script>

Vue-cli

What is Vue cli

It is an official scaffold for quickly generating a vue project template

The pre-defined directory structure and basic code are just like when we create maven project, we can choose to create a skeleton project, which can make our development faster

Main functions:

  • Unified directory structure
  • Local debugging
  • Hot deployment
  • unit testing
  • Integrated packaging Online

Required environment;

node.js installation is brainless. Next, pay attention to the installation environment directory

Confirm successful installation

cmd node-v

npm-v

Baidu image download tutorial is faster to use

Then install npm install vue-cli-g

vue list can view all the templates that can be created

Create project

cmd to the specified directory

Execute command

vue init webpack myvue

Enter all the way and select no

Initialize and run

cd myvue
npm install
npm run dev

Webpack learning

What is Webpack:

It is essentially a static module packer for modern JavaScript applications. When webpack processes applications, it will recursively build a dependency graph, which contains each module required by the application. People will package all these modules into one or more bundle s

CommonsJS

NodeJS on the server side follows the common JS specification. The core idea of changing the specification is to allow modules to synchronously load other modules that need to be relied on through the require method, and then through exports or module Exports to export the interfaces that need to be exposed

require("module");
export.doStuff=function(){};
module.exports=someValue;

Install Webpack

npm install webpack -g
npm install webpack-cli -g

test

webpack -v

webpack-cli -v

Webpack usage

to configure

  • Entry: entry file, which specifies which file the web Pack uses as the entry of the project
  • Output: output the specified webpack and put the processed file in the specified path
  • Module module is used to process various types of files
  • plugins plug-ins, such as hot update and code reuse
  • resolve sets the path to
  • watch monitoring, which is used to set the direct packaging after file changes

1. Create a folder webpack study

2 open webpack study with idea and create the directory of modules to prevent resource files such as JS modules

3. Create a module file under modules, such as hello JS is used to write JS module related code

//Expose a method
exports.sayHi = function(){
    document.write("<div>Hello WebPack</div>");
};

4. Create a module named main under modules JS, which is used to set the entry attribute when packaging

//If you import a module, you can call the methods in the module
var hello = require("./hello");
hello.sayHi();

5. Create webpack.com under the project directory webpack study config. JS configuration file, packaged with webpack command

module.exports = {
    entry: "./modules/main.js",
    output: {
        filename: "./js/bundle.js"
    }
}

6.cmd command uses webpack command to package under the current path

You can see that a dist directory is generated under the webpack study path, and there is a bundle under the js directory js file

7. Create a new index under webpack study HTML file uses src attribute of script tag to introduce bundle js

Open in browser

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script src="dist/js/bundle.js"></script>

</body>
</html>

Vue router routing

Installation:

npm install vue-router --save-dev

introduce

import VueRouter from 'vue-router'

//Display declaration
Vue.use(VueRouter);

Case:

1. Create a new content in the components directory vue,Main. vue, Contemt2. vue

<template>
  <h1>Content page 1</h1>
</template>

<script>
export default {
  name: "Contemt"
}
</script>

<style scoped>

</style>
<template>
    <h1>home page</h1>
</template>

<script>
export default {
  name: "Main"
}
</script>

<style scoped>

</style>
<template>
    <h1>Content page 2</h1>
</template>

<script>
export default {
  name: "Contemt2"
}
</script>

<style scoped>

</style>

2. Create a new router folder at the same level as components

Create a new index under router JS configure routing

import Vue from 'vue'
import VueRouter from 'vue-router'
import C1 from '../components/Contemt'
import C2 from '../components/Contemt2'
import Main from '../components/Main'

//Install routing
Vue.use(VueRouter);

//Configure export routes
export default new VueRouter({
  routes: [
    {
      //Routing path
      path: '/c1',
      //Jump components
      component: C1
    },
    {
      //Routing path
      path: '/c2',
      //Jump components
      component: C2
    },
    {
      //Routing path
      path: '/main',
      //Jump components
      component: Main
    },
  ]
});

3. In main JS

import Vue from 'vue'
import App from './App'
import router from './router' //Automatically scan the routing configuration inside
Vue.config.productionTip = false

new Vue({
  el: '#app',
  //Configure routing
  router,
    
  components: { App },
  template: '<App/>'
})

4. On app Configure display and links in Vue

<template>
  <div id="app">
    <h1>Vue-Router</h1>
    <router-link to="/main">home page</router-link>
    <router-link to="/c1">Content page 1</router-link>
    <router-link to="/c2">Content page 2</router-link>
    <router-view></router-view>
  </div>
</template>

<script>
export default {
  name: 'App',
}
</script>
<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

5. Under the current path, the command line is npm run dev

6. Browser access http://localhost:8080

Vue project practice

1. Create a project named Hello Vue

vue init webpack hello-vue

2. Installation dependency

#Enter project directory
cd hello-vue
#Installing vue - router
npm install vue-router --save-dev
#Install element UI
npm install element-ui -S
#Installation dependency
npm install
#Install SASS loader
cnpm install sass-loader node-sess --save-dev
#Start test
npm run dev

-g means to install the module globally. The specific installation location depends on the location of NPM cinming prefix

– save means to install the module in the project directory and write the dependencies in the dependencies node of the package file. - S is the abbreviation

– save dev means to install the module in the project directory. And write the dependencies in the devDependencies node of the package file

3. Open the project with IDEA, sort out the directory structure, and delete the useless initialization things

assets: used to store resource files

Components store vue functional components

views: store vue view components

Router storage Vue router configuration

4. Create a new main in views vue

<template>
 <h1>home page</h1>
</template>

<script>
export default {
  name: "Main"
}
</script>

<style scoped>

</style>

New login vue

<template>
  <div>
    <el-form ref="loginForm" :model="form" :rules="rules" label-width="80px" class="login-box">
      <h3 class="login-title">Welcome to login</h3>
      <el-form-item label="account number" prop="username">
        <el-input type="text" placeholder="Please enter the account number" v-model="form.username"/>
      </el-form-item>
      <el-form-item label="password" prop="password">
        <el-input type="password" placeholder="Please input a password" v-model="form.password"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" v-on:click="onSubmit('loginForm')">Sign in</el-button>
      </el-form-item>
    </el-form>

    <el-dialog
      title="reminder"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose">
      <span>Please enter your account and password</span>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogVisible = false">determine</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Login",
  data() {
    return {
      form: {
        username: '',
        password: ''
      },

      // For form validation, add prop attribute in El form item element
      rules: {
        username: [
          {required: true, message: 'Account number cannot be empty', trigger: 'blur'}
        ],
        password: [
          {required: true, message: 'Password cannot be empty', trigger: 'blur'}
        ]
      },

      // Dialog box display and hide
      dialogVisible: false
    }
  },
  methods: {
    onSubmit(formName) {
      // Bind validation function for form
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // Using Vue router to route to the specified page is called programmed navigation
          this.$router.push("/main");
        } else {
          this.dialogVisible = true;
          return false;
        }
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.login-box {
  border: 1px solid #DCDFE6;
  width: 350px;
  margin: 180px auto;
  padding: 35px 35px 15px 35px;
  border-radius: 5px;
  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;
  box-shadow: 0 0 25px #909399;
}

.login-title {
  text-align: center;
  margin: 0 auto 40px auto;
  color: #303133;
}
</style>

5. Create a new index in the router directory js

import Vue from 'vue'
import Router from 'vue-router'

import Main from '../views/Main'
import Login from '../views/Login'

Vue.use(Router);

export default new Router({
  routes: [
    {
      path: '/main',
      component: Main
    },
    {
      path: '/login',
      component: Login
    }
  ]
});

6. Configure main js

import Vue from 'vue'
import App from './App'
import router from './router'

import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'

Vue.use(router);
Vue.use(ElementUI)
Vue.config.productionTip = false


new Vue({
  el: '#app',
  router,
  render: h => h(app) //The ElementUI specifies this

});

7. Configure view app vue

<template>
  <div id="app">
    <router-link to="/login">Sign in</router-link>
    <router-view></router-view>
  </div>
</template>
<script>
export default {
  name: 'App'
}
</script>

8.npm run dev test

Error reporting solution:

In package The version of sess loader in JSON is changed to 7.3.1

Then change the version of node sass to 4.14.1

Nested routing

Nested routing is also called sub routing

children:[{

}]

1. Create a user information component and create a profile in the views/user directory View components of Vue;

<template>
   <h1>personal information</h1>
</template>

<script>
export default {
  name: "Profile"
}
</script>

<style scoped>

</style>

2. In the user list component, create a file named list in the views/user directory View components of Vue;

<template>
    <h1>User list</h1>
</template>

<script>
export default {
  name: "List"
}
</script>

<style scoped>

</style>

3. Modify main vue

<template>
  <div>
    <el-container>
      <el-aside width="200px">
        <el-menu :default-openeds="['1']">
          <el-submenu index="1">
            <template slot="title"><i class="el-icon-caret-right"></i>user management </template>
            <el-menu-item-group>
              <el-menu-item index="1-1">
                <!--Where to insert-->
                <router-link to="/user/profile">personal information</router-link>
              </el-menu-item>
              <el-menu-item index="1-2">
                <!--Where to insert-->
                <router-link to="/user/list">User list</router-link>
              </el-menu-item>
            </el-menu-item-group>
          </el-submenu>
          <el-submenu index="2">
            <template slot="title"><i class="el-icon-caret-right"></i>Content management</template>
            <el-menu-item-group>
              <el-menu-item index="2-1">Classified management</el-menu-item>
              <el-menu-item index="2-2">Content list</el-menu-item>
            </el-menu-item-group>
          </el-submenu>
        </el-menu>
      </el-aside>

      <el-container>
        <el-header style="text-align: right; font-size: 12px">
          <el-dropdown>
            <i class="el-icon-setting" style="margin-right: 15px"></i>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item>personal information</el-dropdown-item>
              <el-dropdown-item>Log out</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-header>
        <el-main>
          <!--Show the view here-->
          <router-view />
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>
<script>
  export default {
    name: "Main"
  }
</script>
<style scoped lang="scss">
  .el-header {
    background-color: #B3C0D1;
    color: #333;
    line-height: 60px;
  }
  .el-aside {
    color: #333;
  }
</style>

4. Configure nested routes and modify index. In the router directory JS routing configuration file, put children into main and write sub modules

import Vue from "vue";
import Router from "vue-router";
import Main from "../views/Main";
import Login from "../views/Login";
import UserList from "../views/user/List"
import UserProfile from "../views/user/Profile"
Vue.use(Router);

export default new Router({
  routes: [
    {
      path: '/main',
      component: Main,
      //Route nesting
      children: [
        {path: '/user/profile',component: UserProfile},
        {path: '/user/list',component: UserList}
      ]
    },
    {
      path: '/login',
      component: Login
    }
  ]
});

Start test

Parameter passing and redirection

1. Front end transfer parameters

At this time, we are in main To at the route link position in Vue is changed to: to, in order to use this attribute as an object. Note that the name of the name attribute in the route link must match the name of the name attribute in the route, because in this way, Vue can find the corresponding route path;

<!--name: Pass component name params: To pass parameters, you need to bind objects: v-bind-->
<router-link v-bind:to="{name: 'UserProfile', params: {id: 1}}">personal information</router-link>

2. Modify the routing configuration and add props: true attribute

Mainly the index under router A placeholder such as id is added to the path attribute in JS

{
  path: '/user/profile/:id',
  name: 'UserProfile',
  component: UserProfile,
  props:true
}

3. Front end display

In the component profile to be displayed Receive parameters in Vue

<template>
  <div>
    personal information
    {{ id }}
  </div>
</template>
<script>
    export default {
      props: ['id'],
      name: "UserProfile"
    }
</script>
<style scoped>
</style>

Run test

Component redirection

In index JS

{
  path: '/main',
  name: 'Main',
  component: Main
},
{
  path: '/goHome',
  redirect: '/main'
}

There are two paths defined here, one is / main and the other is / goHome. Where / goHome redirects to the / main path, it can be seen that the redirection does not need to define components

If it is used, it only needs to be in main Vue can set the corresponding path;

<el-menu-item index="1-3">
    <router-link to="/goHome">Back to the home page</router-link>
</el-menu-item>

404 and routing hook

1. Routing mode and 404

There are two routing modes

  • hash: path signed
  • history: path without symbol

The default is the first signed. Using the second method, you need to modify the routing configuration

export default new Router({
  mode: 'history',
  routes: [
  ]
});

404 interface

Create a notfound Vue view component

The content is 404

Modify routing configuration index js

import NotFound from '../views/NotFound'
{
   path: '*',
   component: NotFound
}

2. Routing hook

beforeRouterEnter: execute before entering the route

beforeRouterLeave: execute before leaving the route

In profile In Vue

  export default {
    name: "UserProfile",
    beforeRouteEnter: (to, from, next) => {
      console.log("Ready to enter the personal information page");
      next();
    },
    beforeRouteLeave: (to, from, next) => {
      console.log("Ready to leave the profile page");
      next();
    }
  }

Parameter Description:

  • To: route information to jump
  • from: path information before path jump
  • next: control parameters of the route
  • next() jumps to the next page
  • next('/ path') changes the jump direction of the route to make it jump to another route
  • next(false) returns to the original page
  • Next ((vm) = > {}) is only available in beforeRouteEnter. vm is a component instance

3. Use asynchronous request in hook function

1. Install Axios

npm install --save vue-axios

2.main. Referenced in Axios

import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios)

3. Prepare data. Only the files in our static directory can be accessed, so we put the static files in this directory.

4. Make asynchronous request in beforerouteenter

  export default {
    //The second value method
    // props:['id'],
    name: "UserProfile",
    //Hook function filter
    beforeRouteEnter: (to, from, next) => {
      //Load data
      console.log("Before entering the route")
      next(vm => {
        //Execute the getData method before entering the route
        vm.getData()
      });
    },
    beforeRouteLeave: (to, from, next) => {
      console.log("Before leaving the route")
      next();
    },
    //axios
    methods: {
      getData: function () {
        this.axios({
          method: 'get',
          url: 'http://localhost:8080/static/mock/data.json'
        }).then(function (response) {
          console.log(response)
        })
      }
    }
  }

5. Implementation

Topics: Java Vue