Vue learning from entry to nerve (20,000 words collection)

written in front

A few days ago, I found a giant artificial intelligence learning website. It is easy to understand and humorous. I can't help but share it with you: Artificial intelligence learning website


foreword

Overview : Vue is a front-end progressive framework that can improve the efficiency of front-end development.

Features :

​ Vue can realize the two-way binding between the view and the model through the MVVM mode.

​ Simply put, when the data changes, the page will automatically refresh, and when the page changes, the data will also automatically change.

Three ways to install Vue.js

The article recommended by the big guy here is very detailed.
Three ways to install Vue.js

1. Vue import

Overview : Vue is a JS framework similar to Jquery, so if you want to use Vue, just import the Vue.js file on the current page.

Grammar :

<!-- 在线导入 -->
<!-- 开发环境版本,包含了用帮助的命令行警告 -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<!-- 生产环境版本,优化了尺寸和速度 -->
<script src="https://cdn.jsdelivr.net/npm/vue"></script>

<!-- 本地导入 -->
<script src="node_modules/vue/dist/vue.js"></script>

the case

<div id="app">
    <h1>用户名:<input type="text" v-model="name"/></h1> <br/>
    <h1>您输入的用户名是: {
    
    {
    
    name}}</h1>
</div>

<script type="text/javascript">
    //创建一个Vue对象
    var app = new Vue({
    
    
        //指定,该对象代表<div id="app">,也就是说,这个div中的所有内容,都被当前的app对象管理
        el: "#app",
        //定义vue中的数据
        data: {
    
    
            name: ""
        }
    });
</script>

Two, Vue basic syntax

1. Hook function

**Overview:**The hook function is actually an event defined by Vue in advance, and its function is similar to the init method and distory method of Servlet

Grammar :

<script type="text/javascript">
    var app = new Vue({
    
    
        el:"#app",
        //钩子函数created,该方法在页面显示之后,自动执行
        created() {
    
    
            console.log("created...");
        }
    });
</script>

Supplement: Vue statement cycle and hook function
insert image description here
(1) What is the vue life cycle?

The process of a Vue instance from creation to destruction is the life cycle. That is, a series of processes from the beginning to create, initialize data, compile templates, mount Dom→render, update→render, uninstall, etc. We call this the life cycle of Vue.

(2) What is the role of the vue life cycle?

There are multiple event hooks in the Vue life cycle, which makes it easier for us to form good logic when controlling the entire Vue instance process.

(3) How many stages are there in the vue life cycle?

It can be divided into 8 stages in total: before/after creation, before/after loading, before/after update, and before/after destruction.

(4) Which hooks will be triggered on the first page load?

The beforeCreate, created, beforeMount, mounted hooks will be triggered when the page is loaded for the first time

(5) In which cycle is DOM rendering completed?

DOM rendering is already done in mounted.

(6) Briefly describe which scenarios each cycle is suitable for?

Some ways to use lifecycle hooks:

beforecreate : You can add a loading event at this stage, which is triggered when the instance is loaded;

created : The event when the initialization is completed is written here. If the loading event ends here, the asynchronous request is also suitable for calling here;

mounted : Mount the element and get the DOM node;

updated : If the data is processed uniformly, write the corresponding function here;

beforeDestroy : You can make a confirmation box to confirm the stop event;

nextTick : operate dom immediately after updating data;

2. Interpolation expressions

**Overview:** Interpolation expression users display the data defined in vue on the page. Interpolation expressions allow users to input "JS code snippets"

Grammar :{ { 变量名/对象.属性名 }}

case :

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>vue插值表达式</title>
    <script src="node_modules/vue/dist/vue.js"></script>
</head>
<body>
    <div id="app">
        <h1>欢迎来到-->{
   
   { name }}</h1>
    </div>
    <script type="text/javascript">
        //创建vue对象
        var app = new Vue({
      
      
            //让vue接管div标签
            el:"#app",
            //定义数据,里边包含一个属性name,值为"白大锅"
            data:{
      
      
                name:"白大锅"
            }
        });
    </script>
</body>
</html>

3. Display data (v-text and v-html)

Overview:

​ v-text and v-html are specially used to display data, and their functions are similar to interpolation expressions. v-text and v-html can avoid interpolation flickering problem.

​ When the network speed is relatively slow, using { {}} to display data may cause interpolation flickering problems.

​ Interpolation flickering: When the data is not loaded, the page will display the original { {}}, and the normal data will be displayed after a while.

Grammar :

v-text:<span v-text="msg"></span>	<!-- 相当于<span>{
    
    {msg}}</span> -->
v-html:<span v-html="msg"></span>	<!-- 相当于<span>{
    
    {msg}}</span> -->

difference :

v-text:把数据当作纯文本显示.
v-html:遇到html标签,会正常解析

4. Data two-way binding data (v-model)

Overview:

Vue's two-way binding can be realized: when the data changes, the page will automatically refresh, and when the page changes, the data will also automatically change.

Notice:

  1. Two-way binding, can only bind **"text box, radio button, check box, text field, drop-down list"**, etc.
  2. Text box/radio button/textarea, the bound data is string type
  3. A single check box, bound to boolean type
  4. Multiple check boxes, bound to an array
  5. Select single selection corresponds to a string, and multiple selection corresponds to an array

4.1. Binding text box

code:

<div id="app">
    用户名: <input type="text" v-model="username"/>
</div>
<script type="text/javascript">
    var app = new Vue({
    
    
        el:"#app",
        data:{
    
    
            //该属性值和文本框的value属性值,保持一致
            username:""
        }
    });
</script>

Effect:
insert image description here

4.2. Binding a single check box

code:

<div id="app">
    <input type="checkbox" v-model="agree">同意<br>
</div>
<script type="text/javascript">
    var app = new Vue({
    
    
        el:"#app",
        data:{
    
    
            agree:true
        }
    });
</script>

Effect:
insert image description here

4.3. Binding multiple check boxes

code:

<div id="app">
    <input type="checkbox" value="Java" v-model="language">Java<br>
    <input type="checkbox" value="Python" v-model="language">Python<br>
    <input type="checkbox" value="Swift" v-model="language">Swift<br>
</div>
<script type="text/javascript">
    var app = new Vue({
    
    
        el:"#app",
        data:{
    
    
            //数组中的值,就是被选中的元素的value属性值
            language:["Java","Python"]
        }
    });
</script>

Effect:
insert image description here

4.4.form form data submission

Example: Two cases of passing json format and formData format

<template>
  <div class="from_box">
    <form action="">
      <input type="text"  placeholder="请输入昵称" v-model="formMess.account">
      <input type="password" placeholder="请输入密码" v-model="formMess.act_pwd">
      <input type="text" placeholder="请输入手机号" v-model="formMess.phone">
    </form>
    <span class="but" @click="onSubmit()">提交</span>
  </div>
</template>
 
<script>
import axios from 'axios';
 
export default {
    
    
  name: "from",
  data() {
    
    
    return {
    
    
    	formMess:{
    
    
	    "account":"",
	    "act_pwd":"",
	    "phone":""
	}
    };
  },
  methods: {
    
    
    onSubmit() {
    
    
      /* json格式提交: */
      // let formData = JSON.stringify(this.formMess);
 
      /* formData格式提交: */
      let formData = new FormData();
      for(var key in this.formMess){
    
    
        formData.append(key,this.formMess[key]);
      }
 
        axios({
    
    
	    method:"post",
	    url:"xxxxxxx",
	    headers: {
    
    
		  "Content-Type": "multipart/form-data"
	    },
	    withCredentials:true,
	    data:formData
	}).then((res)=>{
    
    
            console.log(res);
        });
    }
  }
};
</script>
 
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less">
.from_box{
    
    
  form{
    
    
    width:90%;
    margin: auto;
    border:.01rem solid gray;
    display: flex;
    flex-wrap: wrap;
    input{
    
    
      width:80%;
      height:.5rem;
      margin-bottom: .2rem;
      border:.01rem solid black;
      height:.5rem;
    }
  }
  .but{
    
    
    font-size: .14rem;
    margin-left:5%;
  }
}
</style>

5. Event processing (v-on)

5.1. Event binding (v-on)

Overview:

Vue can also bind events to page elements.

Grammar :

<!--完整写法-->
<button v-on:事件名="函数名/vue表达式">点我</button>
<!--简化写法-->
<button @事件名="函数名/vue表达式">点我</button>

Notice:

​ Vue supports all known events in html. Such as: @click, @submit, etc., but the name of the event does not contain on

case :

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>vue事件处理</title>
    <script src="node_modules/vue/dist/vue.js"></script>
</head>
<body>
    <div id="app">
        <button @click="show">点我</button>
    </div>
    <script type="text/javascript">
        //创建vue对象
        var app = new Vue({
    
    
            //获取id为app的元素,该元素被vue对象所管理.只有被vue对象管理的标签,其内部才允许书写vue语法
            el:"#app",
            //定义vue的方法
            methods:{
    
    
                //定义show方法,弹出提示框
                show() {
    
    
                    alert("Hello Vue!!!");
                }
            }
        });
    </script>
</body>
</html>

5.2. Event modifiers

**Overview: **Event modifiers mainly limit the scope of events

Grammar :

<button @事件名.事件修饰符="函数名/vue表达式">点我</button>

Classification:

.stop :阻止事件冒泡, 也就是当前元素发生事件,但当前元素的父元素不发生该事件
.prevent :阻止默认事件发生
.capture :使用事件捕获模式, 主动获取子元素发生事件, 把获取到的事件当自己的事件执行
.self :只有元素自身触发事件才执行。(冒泡或捕获的都不执行)
.once :只执行一次

case :

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>vue事件处理</title>
    <script src="node_modules/vue/dist/vue.js"></script>
</head>
<body>
    <div id="app">
        <button @click="show">点我</button>
    </div>
    <script type="text/javascript">
        //创建vue对象
        var app = new Vue({
    
    
            //获取id为app的元素,该元素被vue对象所管理.只有被vue对象管理的标签,其内部才允许书写vue语法
            el:"#app",
            //定义vue的方法
            methods:{
    
    
                //定义show方法,弹出提示框
                show() {
    
    
                    alert("Hello Vue!!!");
                }
            }
        });
    </script>
</body>
</html>

6. Loop traversal (v-for)

6.1. Traversing an array

Grammar :

v-for="item in items"
v-for="(item,index) in items"

items: the array to be iterated
item: the variable name to store the array elements
index: the index of the current element iterated to, starting from 0.

code :

<div id="app">
	<ul>
        <li v-for="(user, index) in users">
        	{
    
    {
    
    index}}--{
    
    {
    
    user.name}}--{
    
    {
    
    user.age}}--{
    
    {
    
    user.gender}}
        </li>
	</ul>
</div>
<script>
    var app = new Vue({
    
    
        el:"#app",//el即element,要渲染的页面元素
        data: {
    
    
            users:[
                {
    
    "name":"白卓冉","age":8,"gender":"男"},
                {
    
    "name":"白大锅","age":12,"gender":"女"},
                {
    
    "name":"白仙女","age":4,"gender":"男"}
            ]
        }
    });
</script>

6.2. Traversing objects

Grammar :

v-for="value in object"
v-for="(value,key) in object"
v-for="(value,key,index) in object"

value, the value key of the object , the key index
of the object , the index, starting from 0

Code :

<div id="app">
	<ul>
        <li v-for="(value,key,index) in person">
        	{
    
    {
    
    index}}--{
    
    {
    
    key}}--{
    
    {
    
    value}}
        </li>
	</ul>
</div>
<script>
    var app = new Vue({
    
    
        el:"#app",//el即element,要渲染的页面元素
        data: {
    
    
            person:{
    
    "name":"白大锅", "age":3, "address":"中国"}
        }
    });
</script>

6.3.key

Overview:

​ :key is generally used together with v-for. It is used to ensure the order of elements in the traversed array under certain circumstances.

case:

<div id="app">
    <button @click="add">添加</button>
    <ul>
        <li v-for="name in list">
            <input type="checkbox"> {
   
   {name}}
        </li>
    </ul>
</div>
<script>
    var app = new Vue({
      
      
        el: '#app',
        data: {
      
      
            list: ["孙悟空", "猪八戒", "沙和尚"]
        },
        methods: {
      
      
            add() {
      
      
                //注意这里是unshift,向数组的头部添加一个元素
                this.list.unshift("唐僧");
            }
        }
    });
</script>

Effect:
insert image description here
Solution:

<div id="app">
    <button @click="add">添加</button>
    <ul>
        <!-- 添加:key即可. 注意,key中的值必须是唯一且不会改变的值-->
        <li v-for="name in list" :key="name">
            <input type="checkbox"> {
   
   {name}}
        </li>
    </ul>
</div>

7. Judgment grammar (v-if and v-show)

Overview:

v-if and v-show can decide whether to display the specified content according to the result of the condition.

​ v-if: When the condition is not met, the element will not exist.

​ v-show: When the condition is not met, the element will not be displayed (but still exists).

case :

<div id="app">
	<button @click="show = !show">点我</button>
	<h1 v-if="show">Hello v-if.</h1>
    <h1 v-show="show">Hello v-show.</h1>
</div>
<script>
    var app = new Vue({
      
      
        el:"#app",
        data: {
      
      
        	show:true
        }
    });
</script>

8. Display data (v-bind)

Overview:

The function of v-bind is similar to the interpolation expression, except that v-bind is mainly used to dynamically set the attribute value of the label

Grammar :

<!--完整写法-->
<标签名 v-bind:标签属性名="vue实例中的数据属性名"/>
<!--简化写法-->
<标签名 :标签属性名="vue实例中的数据属性名"/>

case :

<div id="app">
    <input type="button" :value="msg"/>
</div>
<script type="text/javascript">
    var app = new Vue({
      
      
        el:"#app",
        data:{
      
      
           msg:"我是按钮"
        }
    });

</script>

9. Vue page jump (two methods)

9.1. Method 1 (label implementation)

<router-link :to="{name: 'bookshelf', params: { entityId: this.entityId } }"
             :class="{
     
     'flex-item-1':'flex-item-1',cur:tabs[0].isShow}" href="javascript:">
              <span class="tabNav-ico tabNav-book"></span>
              <span class="tabNav-txt">书 架</span>

</router-link>

9.1. Method 2 (implementation of this.$router.push())

When this.$router.push() has only one parameter, it defaults to the jump address. Up to two parameters can be passed. The second parameter is the address parameter.

<a @click="toIndex" :class="{'flex-item-1':'flex-item-1',cur:tabs[2].isShow}" href="javascript:">
      <span class="tabNav-ico tabNav-home"></span>
      <span class="tabNav-txt">首 页</span>

</a>

toIndex: function(){
    
    
        this.$router.push("/?entityId="+ localStorage.getItem("entityId"));

}

Three, Vue other syntax

3.1. Computed properties

Overview : A computed property is a pre-defined method that can be seen as a special value that can be used in interpolation expressions.

Grammar :

 var app = new Vue({
    
    
     el:"#app",
     //计算属性必须放在Vue的computed中
     computed:{
    
    
         //定义计算属性
         属性名(){
    
    
             return "返回值";
         }
     }
});

case:

<div id="app">
    <h1>{
    
    {
    
    birth}}</h1>
    <h1 v-text="birth"></h1>
    <h1 v-html="birth"></h1>
</div>
<script type="text/javascript">
    var app = new Vue({
    
    
        el:"#app",
        computed:{
    
    
            //定义一个birth方法,该方法就是一个计算属性,可以在插值表达式中使用
            birth(){
    
    
                let date = new Date();
                let year = date.getFullYear();
                let month = date.getMonth()+1;
                let day = date.getDay();
                return year + "-" + month + "-" + day;
            }
        }
    });
</script>

3.2.watch monitoring

Overview :

Watch can monitor simple property values ​​and changes in property values ​​in objects.

Watch is similar to the onchange event, which can perform certain operations when the attribute value is modified.

Grammar :

var app = new Vue({
    
    
    el:"#app",
    data:{
    
    
        message:"白大锅",
        person:{
    
    "name":"heima", "age":13}
    },
    //watch监听
    watch:{
    
    
        //监听message属性值,newValue代表新值,oldValue代表旧值
        message(newValue, oldValue){
    
    
        	console.log("新值:" + newValue + ";旧值:" + oldValue);
        },
        //监控person对象的值,对象的监控只能获取新值
        person: {
    
    
            //开启深度监控;监控对象中的属性值变化
            deep: true,
            //获取到对象的最新属性数据(obj代表新对象)
            handler(obj){
    
    
                console.log("name = " + obj.name + "; age=" + obj.age);
            }
        }
    }
});

Four, Vue components

4.1. Basic usage

Overview:

Components are similar to templates and modules. When a project needs to reuse a certain module (head, tail, news...), the module can be extracted into a component, and the component can be registered and referenced in other pages.

case:

<div id="app">
    <!--使用组件(组件名称),如果组件名称中有大写字母,如"myList",则这里需要书写<my-list>-->
    <counter></counter>
    <counter></counter>
</div>
<script type="text/javascript">
    //定义组件
    const counterTemp = {
      
      
        //定义组件的模版
        template:`<button @click='num++'>你点击了{
       
       {num}}次</button>`,
        //定义组件中使用到的数据属性
        data(){
      
      
           return {
      
      
              num:0
           }
        } 
    };    

    //全局注册组件:在所有的vue实例中都可以使用组件
    //参数1:组件名称,参数2:具体的组件
    //Vue.component("counter", counterTemp);
    
    var app = new Vue({
      
      
        el:"#app",
        //局部注册组件: 只能在当前Vue实例中使用
        components:{
      
      
            //组件名称:具体组件
            counter: counterTemp
        }
    });
</script>

Notice:

  1. In the template of the component, only one root tag can be written
  2. The definition of the component must be placed before Vue creates the object, otherwise an error will be reported

4.2. Parent component to child component communication

Overview:

Child components cannot directly use the data in the parent component. If they need to use it, the parent component must pass the data to the child component.

Essence: Let the properties in the child component be associated and bound with the properties in the parent component, and then the child component uses this property, so that data can be passed

significance:

The data in the parent component can be updated and passed to the child component

Example:

<div id="app">
     <!-- 把父组件中的count传递给子组件的number属性,把父arr传递给子ids,把父p传递给子person -->
    <aaa :number="count" :ids="arr" :person="p"></aaa>
</div>

<script>
    var aaa = {
      
      
        //定义组件的模版
        template: `<h2>{
       
       {num}}---{
       
       {number}}--{
       
       {ids}}--{
       
       {person}}</h2>`,
        //定义组件中使用到的数据属性
        data() {
      
      
            return {
      
      
                num: 0
            }
        },
        //给组件添加属性
        props: {
      
      
            //普通属性number
            number: "",
            //数组属性ids
            ids: [],
            //对象属性person
            person: {
      
      }
            /*
            *	//以上属性还可以书写为以下格式
            *	items:{
            *        //数据类型,如果是数组则是Array,如果是对象则是Object
            *       type:Array,
            *       //默认值
            *       default:[]
            *	}
            */
        }
    };

    //注册:全局注册
    Vue.component("aaa", aaa);

    var app = new Vue({
      
      
        el: "#app",
        data: {
      
      
            count: 5,
            arr: [1, 2, 3],
            p: {
      
      username: "zhangsan", age: 23}
        }
    });
</script>

4.3. Child components communicate with parent components

Overview:

Child components cannot directly pass data to the parent component. Nor can they manipulate the data in the parent component, nor can they call the methods in the parent component.

Therefore, the so-called communication between the child component and the parent component is actually to find a way for the child component to call the method of the parent component, and then respond to the data in the parent component.

significance:

Child components can call methods in parent components

Example:

<div id="app">
    <h1>父组件中:app_num={
   
   {app_num}}</h1>
    <!-- 把父组件的add方法,绑定给子组件的aaa属性,绑定方法使用@属性名="方法名" -->
    <!-- 把父组件的rem方法,绑定给子组件的bbb属性,绑定方法使用@属性名="方法名 -->
    <!-- 把父组件的app_num变量,绑定给子组件的counter_num属性,绑定变量使用:属性名="方法名 -->
    <counter @aaa="add" @bbb="rem" :counter_num="app_num"></counter>
</div>

<script>
    //定义一个组件(模版)
    let counter = {
      
      
        template: `
             <div>
                   <h1>子组件中:counter_num={
       
       {counter_num}}</h1>
                   <input type="button" @click="fun1" value="+"/>
                   <input type="button" @click="fun2" value="-"/>
            </div>
                `,
        props:{
      
      
            //定义属性counter_num,用来接收父组件传递的数据
            counter_num:null,
            //定义aaa属性,用来绑定父组件的方法,当然,该定义也可以省略
            aaa:function(){
      
      },
            //定义bbb属性,用来绑定父组件的方法,当然,该定义也可以省略
            bbb:function(){
      
      },
        },       
        methods:{
      
      
            fun1(){
      
      
                //找到aaa属性所绑定的那个方法,执行那个方法
                return this.$emit("aaa");
            },
            fun2(){
      
      
                //找到bbb属性所绑定的那个方法,执行那个方法
                return this.$emit("bbb");
            }
        }
    }

    var app = new Vue({
      
      
        el: '#app',
        data: {
      
      
            app_num: 0
        },
        components: {
      
      
            counter
        },
        methods:{
      
      
            add(){
      
      
                this.app_num++;
            },
            rem(){
      
      
                this.app_num--;
            }
        }
    });
</script>

Five, axios asynchronous request

5.1 axios overview

Overview:

Axios is a promise-based HTTP library, mainly used to: send asynchronous requests to obtain data .

Common methods:

​ axios(config)

​ axios.get(url, [config])

​ axios.post(url, [data])

Send data config common parameters:

{
    
    
    url: '请求的服务器',
	method: '请求方式', // 默认是 get
    // GET请求参数
    params: {
    
    
    	参数名: 参数值
    },
	// POST请求参数, 如果使用axios.post,则参数在url之后直接书写,不需要该位置传递参数
    data: {
    
    
    	参数名: 参数值
    },
	// 响应数据格式,默认json
	responseType: 'json'
}

Response data common parameters:

{
    
    
    data: {
    
    },		//真正的响应数据(响应体)
    status: 200,	//响应状态码
    statusText: 'OK',	 //响应状态描述
    headers: {
    
    },	//响应头
    config: {
    
    }		//其他配置信息
}

5.2. Get request

var app = new Vue({
    
    
    el: "#app",
    data: {
    
    
        user: {
    
    }
    },
    //当页面加载完毕后
    created() {
    
     
        //发送GET请求axios.get("请求路径",{ config });
       axios.get("请求路径",{
    
    
            //get请求参数
            params: {
    
    
                name:"zhangsan",
                age:23
            },
            //响应数据格式为"json"
            responseType: 'json'
        }).then(res => {
    
    
            //打印响应数据
            console.log(res);
            //把响应数据赋值给Vue中的user属性
            app.user = res.data;
        }).catch(err => {
    
    
            //打印响应数据(错误信息)
            console.log(err);
        });
    }
});

5.3. Post request

var app = new Vue({
    
    
    el: "#app",
    data: {
    
    
        user: {
    
    }
    },
    //当页面加载完毕后
    created() {
    
     
        //发送POST请求axios.post("请求路径",{ 参数 });
        axios.post("请求路径",{
    
    
                name:"zhangsan",
                age:23
            }).then(res => {
    
    
                console.log(res);
                app.user = res.data;
            }).catch(err => {
    
    
                console.log(err);
            });
    }
});

5.4. Cross-domain request

Cross-domain request: If an asynchronous request is sent in the front-end js, the requested address is different from the current server's ip or port number, which is a cross-domain request.

Cross-domain requests need to be enabled on the service provider to allow cross-domain requests
insert image description here

六、VueJ's Ajax

6.1.vue-resource

vue-resource is a plugin for Vue.js that provides services for making web requests and processing responses using XMLHttpRequest or JSONP. When vue was updated
to 2.0, the author announced that he would no longer update vue-resource, but recommended axios. Here you can learn about vue-resource.
github of vue-resource: https://github.com/pagekit/vue-resource

6.2.axios

Axios is a promise-based HTTP library that can be used in browsers and node.js
Axios's github: https://github.com/axios/axios

6.2.1. Introducing axios

The first is to introduce axios. If you use es6, you only need to install the axios module and then
import axios from 'axios';
//Installation method
npm install axios
//or
bower install axios

Of course, you can also use script to import

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

6.2.2. get request

//通过给定的ID来发送请求
axios.get('/user?ID=12345')
.then(function(response){
    
    
console.log(response);
}).catch(function(err){
    
    
console.log(err);
});
//以上请求也可以通过这种方式来发送
axios.get('/user',{
    
    
params:{
    
    
ID:12345
}
}).then(function(response){
    
    
console.log(response);
}).catch(function(err){
    
    
console.log(err);
});

6.2.3. post request

axios.post('/user',{
    
    
firstName:'Fred',
lastName:'Flintstone'
})
.then(function(res){
    
    
console.log(res);
})
.catch(function(err){
    
    
console.log(err);
});

For convenience, aliases are provided for all supported request methods

axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])

7. Comprehensive case

7.1. Requirements

Complete user query and modification operations

7.2. Database design and table structure

CREATE DATABASE vuejsdemo;
USE vuejsdemo;
CREATE TABLE USER(
id INT PRIMARY KEY AUTO_INCREMENT,
age INT,
username VARCHAR(20),
PASSWORD VARCHAR(50),
email VARCHAR(50),
sex VARCHAR(20)
)

User class

public class User {
    
    
private Integer id;
private String username;
private String password;
private String sex;
private int age;
private String email;
省略getter/setter

7.3. Server side

7.3.1. Configuration file

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
	http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
	version="3.1"
	metadata-complete="true">
	<!-- 手动指定 spring 配置文件位置 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:applicationContext.xml</param-value>
	</context-param>
	<!-- 配置 spring 提供的监听器,用于启动服务时加载容器 。
	该间监听器只能加载 WEB-INF 目录中名称为 applicationContext.xml 的配置文件 -->
	<listener>
		<listener-class>
			org.springframework.web.context.ContextLoaderListener
		</listener-class>
	</listener>
	<!-- 配置 spring mvc 的核心控制器 -->
	<servlet>
		<servlet-name>springmvcDispatcherServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<!-- 配置初始化参数,用于读取 springmvc 的配置文件 -->
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:springmvc.xml</param-value>
		</init-param>
		<!-- 配置 servlet 的对象的创建时间点:应用加载时创建。取值只能是非 0 正整数,表示启动顺
		序 -->
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>springmvcDispatcherServlet</servlet-name>
		<url-pattern>*.do</url-pattern>
	</servlet-mapping>
	<!-- 配置 springMVC 编码过滤器 -->
	<filter>
		<filter-name>CharacterEncodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<!-- 设置过滤器中的属性值 -->
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
		<!-- 启动过滤器 -->
		<init-param>
			<param-name>forceEncoding</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<!-- 过滤所有请求 -->
	<filter-mapping>
		<filter-name>CharacterEncodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.htm</welcome-file>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>
</web-app>

springmvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans.xsd
	http://www.springframework.org/schema/mvc
	http://www.springframework.org/schema/mvc/spring-mvc.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context.xsd">
	<!-- 配置创建 spring 容器要扫描的包 -->
	<context:component-scan base-package="com.itheima">
		<!-- 制定扫包规则 ,只扫描使用@Controller 注解的 JAVA 类 -->
		<context:include-filter type="annotation"
		expression="org.springframework.stereotype.Controller"/>
	</context:component-scan>
	<mvc:annotation-driven></mvc:annotation-driven>
</beans>

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans.xsd
	http://www.springframework.org/schema/tx
	http://www.springframework.org/schema/tx/spring-tx.xsd
	http://www.springframework.org/schema/aop
	http://www.springframework.org/schema/aop/spring-aop.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context.xsd">
	<!-- 配置 spring 创建容器时要扫描的包 -->
	<context:component-scan base-package="com.itheima">
	<!--制定扫包规则,不扫描@Controller 注解的 JAVA 类,其他的还是要扫描 -->
		<context:exclude-filter type="annotation"
		expression="org.springframework.stereotype.Controller"/>
	</context:component-scan>
	<!-- 加载配置文件 -->
	<context:property-placeholder location="classpath:db.properties"/>
	<!-- 配置 MyBatis 的 Session 工厂 -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<!-- 数据库连接池 -->
		<property name="dataSource" ref="dataSource"/>
		<!-- 加载 mybatis 的全局配置文件 -->
		<property name="configLocation" value="classpath:SqlMapConfig.xml"/>
	</bean>
	<!-- 配置数据源 -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="driverClass" value="${jdbc.driver}"></property>
		<property name="jdbcUrl" value="${jdbc.url}"></property>
		<property name="user" value="${jdbc.username}"></property>
		<property name="password" value="${jdbc.password}"></property>
	</bean>
	<!-- 配置 Mapper 扫描器 -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.itheima.dao"/>
	</bean>
	<tx:annotation-driven/>
	<!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource"/>
	</bean>
</beans>

db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/vuejsDemo
jdbc.username=root
jdbc.password=root

7.3.2.Controller

@RequestMapping("/user")
@Controller
@ResponseBody
public class UserController {
    
    
	@Autowired
	private IUserService userService;
	@RequestMapping(value="/findAll.do")
	public List<User> findAll() {
    
    
		return userService.findAll();
	}
	@RequestMapping(value="/findById.do")
	public User findById(Integer id) {
    
    
		return userService.findById(id);
	}
	@RequestMapping(value="/update.do")
	public User update(@RequestBody User user) {
    
    
		return userService.update(user);
	}
}

7.3.3.Dao

public interface IUserDao {
    
    
	@Select("select * from user")
	public List<User> findAll();
	@Select("select * from user where id=#{id}")
	User findById(Integer id);
	@Update("update user set username=#{
    
    username},password=#{
    
    password},sex=#{
    
    sex},age=#
	{
    
    age},email=#{
    
    email} where id=#{
    
    id}")
	void update(User user);
}

7.4. Client

7.4.1.user.html page

The reasons for various page codes are temporarily unable to provide ideas, probably these are hee hee~

7.4.2.user.js

var vue = new Vue({
    
    
	el: "#app",
	data: {
    
    
		user: {
    
    id:"",username:"aaa",password:"",age:"",sex:"",email:""},
		userList: []
	},
	methods: {
    
    
		findAll: function () {
    
    
			var _this = this;
			axios.get("/vuejsDemo/user/findAll.do").then(function (response) {
    
    
				_this.userList = response.data;
				console.log(_this.userList);
			}).catch(function (err) {
    
    
				console.log(err);
			});
		},
		findById: function (userid) {
    
    
			var _this = this;
			axios.get("/vuejsDemo/user/findById.do", {
    
    
				params: {
    
    
					id: userid
				}
			}).then(function (response) {
    
    
				_this.user = response.data;
				$('#myModal').modal("show");
			}).catch(function (err) {
    
    
			});
		},
		update: function (user) {
    
    
			var _this = this;
			axios.post("/vuejsDemo/user/update.do",_this.user).then(function (response) {
    
    
				_this.findAll();
			}).catch(function (err) {
    
    
			});
		}
	},
	created(){
    
    
		this.findAll();
	}
});

There are roads in the mountains of books, hard work, endless learning, hard work, and endless learning~
This article is from the introduction of Vue to the gradual deepening, and then to the use of comprehensive cases in combination with Java
. ~)

Guess you like

Origin blog.csdn.net/weixin_45735355/article/details/118931768