vue学习

1.vue.js的快速入门使用

1.1 vue.js库的下载

vue.js是目前前端web开发最流行的工具库,由尤雨溪在2014年2月发布的。

另外几个常见的工具库:react.js /angular.js/jQuery

官方网站:

jQuery和Vue的定位是不一样的:

"""
jQuery的定位:
(1)获取元素;
(2)完成特效;
Vue的定位:
(1)方便操作;
(2)完成特效
"""

1.2 vue.js库的基本使用

github下载地址:https://cn.vuejs.org/v2/guide/installation.html

第一个vue程序

<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="content-type" charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>第一个Vue程序</title>
    <script src="vue.min.js"></script>
    <script>
        window.onload = function () {
            //窗口预加载,等待html加载完毕后执行
            let vm = new Vue({
                el: '#app', //设置Vue对象操作的标签范围
                data: { //data是展示到html页面渲染的数据
                    message: 'hello world!'
                },
            })
        }
    </script>
</head>
<body>
<div id="app">
    <!--在双标签中显示数据要通过{{ }}来完成-->
    {{ message }}
</div>
</body>

总结

1.Vue的使用始于Vue一个对象的创建
let vm = new Vue({
	el:'#id_box',
	data:{
		message='hello world~',
		num=66,
		url='http://www.mzitu.com',
},
})

2.创建vue对象时需要传递参数,是json对象,json对象至少要有两个属性
{el:'#id_box',data:{message='hello world~',},}

el属性:设置Vue对象可以操作的标签范围,其值一般是css的id选择器
data属性:保存vue.js要显示到html页面的数据

3. vue.js要控制器的内容范围,必须先通过id来设置。
  <div id="app">
      <h1>{{message}}</h1>
      <p>{{message}}</p>
  </div>

1.3 vue.js的M-V-VM思想

MVVM(Model-View-ViewModel)是一种基于前端开发的架构模式。

Model 指代的就是vue对象的data属性里面的数据。这里的数据要显示到页面中。

View 指代的就是vue中数据要显示的HTML页面,在vue中,也称之为“视图模板” 。

ViewModel 指代的是vue.js中我们编写代码时的vm对象了,它是vue.js的核心,负责连接 View 和 Model,保证视图和数据的一致性,所以前面代码中,data里面的数据被显示中p标签中就是vm对象自动完成的。

MVVM模型的代码剖析

<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="content-type" charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>MVVVM模型</title>
    <script src="vue.min.js"></script>
    <script>
        window.onload = function () {
            let vm = new Vue({
                el: '#id_choice',
                data: {
                    message: 'Vue的初步使用',
                    day: new Date().getDate(),
                },
            });
        }
    </script>
</head>
<body>
<div id="id_choice">
	<!-- 在双标签中显示数据要通过{{  }}来完成 -->
    <p>{{ message }}</p>
    <!-- 在表单输入框中显示数据要使用v-model来完成 -->
    <input v-model="day">
    <p>{{ day }}</p>
</div>
</body>
</html>

我们可以通过vm对象来访问el和data属性,也可以直接访问data里面的数据。

console.log(vm.$el)        # #app  vm对象可以控制的范围
console.log(vm.$data);     #    vm对象要显示到页面中的数据
console.log(vm.$data.message);  # 访问data里面的数据
console.log(vm.message);   # 这个 message就是data里面声明的数据,也可以使用 vm.变量名显示其他数据,message只是举例.

总结:

1.将data中的数据输出到双标签中,要使用`{{ }}`
<p>{{ message }}</p>
2.将data中的数据输出到input框中,要使用`v-model`
<div id='#app'>
	<input v-model="message">
</div>

# vm对象的同步更新
在使用v-model将data中的数据输出到input框中,如果用户修改表单元素的值,则data里面对应数据的值也会随之发生改变,甚至,页面中凡是使用了这个数据都会发生变化。

vue.js如何修改模板语法,比如将{{}}改成{[]},使用delimiters参数

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="vue.min.js"></script>
    <!--<script>Vue.config.delimiters = ["{[","]}"]</script>-->
</head>
<body>
<div id="box">
    <a :href="url">百度</a>
    密码:<input :type="type" v-model="password" >
    <button @click="change">显示密码</button>
</div>
<script>
    var vm = new Vue({
        el: '#box',
        delimiters: ["{[", "]}"],
        data: {
            url: 'http://www.baidu.com',
            type: 'password',
            password: '',
        },
        methods: {
            change() {
                if(this.type === 'text'){
                    this.type = 'password';
                }else {
                    this.type = 'text';
                }
            }
        }
    });
</script>
</body>
</html>

1.4 显示数据

  • 在双标签中显示纯文本数据一般通过{{ }}来完成数据显示,双括号中还可以支持js表达式和符合js语法的代码,例如函数调用.

  • 在表单输入框中显示数据要使用v-model来完成数据显示

  • 如果双标签的内容要显示的数据包含html代码,则使用v-html来完成

<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="content-type" charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>显示数据</title>
    <script src="vue.min.js"></script>
    <script>
        window.onload = function () {
            let vm = new Vue({
                el: '#app',
                data: {
                    str: 'hello',
                    ageOfJason: 18,
                    ageOfEgon: 78,
                    name: 'surpass',
                    price: 7.6,
                    url: 'http://www.mzitu.com',
                    img:'<img src="images/shendan.png">',
                },
            })
        }
    </script>
<body>
<div id="app">
    <p>{{ str.split("").reverse().join("")}}</p>
    <p>egon和jason的年龄比较:{{ ageOfJason>ageOfEgon?ageOfJason:ageOfEgon }}</p>
    <div>
        <input type="text" v-model="name">
    </div>
        //toFixed() 方法可把 Number 四舍五入为指定小数位数的数字。
    <p>{{ (price+0.8).toFixed(2) }}</p>
    <span v-html="img"></span>
</div>
</body>
</html>

总结:

"""
1. 可以在普通标签中使用{{  }} 或者 v-html 来输出data里面的数据   
2. 可以在表单标签中使用v-model属性来输出data里面的数据,同时还可以修改data里面的数据
"""

2 常用的指令

定义: 指令(Directives) 是带有“v-”前缀的特殊属性。每一个指令在vue中都有固定的作用。

在vue中,常见的指令有:

v-if、
v-model、
v-for
...

因为vue的历史版本原因,所以有一部分指令都有两种写法:

vue1.x写法             vue2.x的写法
v-html         ---->   v-html
{{ 普通文本 }}          {{普通文本}}
v-bind:属性名   ---->   :属性
v-on:事件名     ---->   @事件名

2.1 属性操作

格式:

<标签名 :标签属性="data属性"></标签名>

显示wifi密码的案例

    <title>wifi密码显示案例</title>
    <script src="vue.min.js"></script>
    <script>
        window.onload = function () {
            let vm = new Vue({
                el: '#app',
                data: {
                    url: 'https://i.mmzztt.com/thumb/2020/06/234779_236.jpg',
                    title: '兄弟们身体还好吗',
                    type: 'password',
                },
            });
        }
    </script>
</head>
<body>
<div id="app">
    <img :src="url" alt="" :title="title"><br>
    <input :type="type" placeholder="请输入wifi密码" ><button @click="type='text'">显示密码</button>
</div>
</body>
</html>

密码显示案例二

<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="content-type" charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Title</title>
    <script src="vue.min.js"></script>
    <script>
        window.onload = function () {
            let vm = new Vue({
                el: '#app',
                data: {
                    url: 'https://i.mmzztt.com/thumb/2020/06/218931_236.jpg',
                    title: '兄弟们医院WiFi怎么样',
                    type: 'password',
                    password: '',
                    text: '显示密码'
                },
                methods: {
                    change: function () {
                        if (this.type === 'password') {
                            this.type = 'text';
                            this.text = '隐藏密码';
                        } else {
                            this.type = 'password';
                            this.text = '显示密码';
                        }
                    }
                },
            });
        }
    </script>
</head>
<body>
<div id="app">
    <img :src="url" alt="" :title="title"><br>
    <input :type="type" v-model="password">
    <button @click="change">{{ text }}</button>

</div>
</body>
</html>

2.2 事件的绑定

1. 使用@事件名来进行事件的绑定
   <button @click="++num">{{ num }}</button>

2. 绑定的事件的事件名,全部都是js的事件名:
   @submit   --->  onsubmit
   @focus    --->  onfocus
   @blur     --->  onblur
   @click    --->  onclick
   ....

案例:购物商城商品的添加或减少

<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="content-type" charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Title</title>
    <script src="vue.min.js"></script>
    <script>
        window.onload = function () {
            let vm = new Vue({
                el: '#app',
                data: {
                    goods: {
                        num: 8,
                        disabled: false,
                    },
                    add_text: '+',
                    sup_text: '-',
                },
                methods: {
                    sub: function () {
                        this.goods.disabled = --this.goods.num < 1;
                    },
                    add: function () {
                        this.goods.disabled = false;
                        this.goods.num++
                    }
                },

            });
        }
    </script>
</head>
<body>
<div id="app">
    <button :disabled="goods.disabled" @click="sub">{{ sup_text }}</button>
    <br>
    <input type="text" v-model="goods.num"><br>
    <button @click="add">{{ add_text }}</button>
</div>
</body>
</html>

2.3 样式的操作

操作样式,其本质就是操作属性

2.3.1 控制标签的class类名

格式:
   <h1 :class="值">元素</h1>  值可以是字符串、对象、对象名、数组

示例1:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="content-type" charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Title</title>
    <script src="vue.min.js"></script>
    <style>
        .box1 {
            color: red;
            border: 1px solid #000;
        }

        .box2 {
            background-color: orange;
            font-size: 32px;
        }
    </style>
</head>
<body>
<div id="box">
    <p :class="{box1:myclass1}">一个段落1</p>
    <p :class="{box1:myclass2,box2:myclass3}" @click="myclass3=!myclass3">一个段落2</p>
</div>
<script>
    let vm = new Vue({
        el: '#box',
        data: {
            myclass1: false,
            myclass2: false,
            myclass3: false,
        },
    })
</script>
</body>
</html>

示例2:

    <script src="vue.min.js"></script>
    <style>
        .box4 {
            background-color: red;
        }

        .box5 {
            color: green;
        }
    </style>
</head>
<body>
<div id="app">
    <button @click="mycls.box4=!mycls.box4">改变背景</button>
    <button @click="mycls.box5=!mycls.box5">改变字体颜色</button>
    <p :class="mycls">第二个段落</p>
</div>
<script>
    let vm2 = new Vue({
        el: "#app",
        data: {
            mycls: {
                box4: false,
                box5: true
            },
        }
    })
</script>
</body>

示例3

    <script src="vue.min.js"></script>
    <style>
        .box6 {
            background-color: red;
        }

        .box7 {
            color: green;
        }

        .box8 {
            border: 1px solid yellow;
        }
    </style>
</head>
<body>
<div id="app2">
    <p :class="[mycls1,mycls2]">第三个段落</p>
</div>
<script>
    let vm3 = new Vue({
        el: "#app2",
        data: {
            mycls1: {
                box6: true,
                box7: true,
            },
            mycls2: {
                box8: true,
            }
        }
    })
</script>
</body>

三种方式中最常用的是第二种

1. 给元素绑定class类名,最常用的就是第二种。 

2.3.2 标签控制style样式

格式1:值是json对象,对象写在:style的属性中

<div id="app">
    <div :style="{color:activecolor,fontsize:fontsize+'px'}">西部数据
    </div>
</div>
<script>
    let vm = new Vue({
        el: '#app',
        data: {
            activecolor: 'red',
            fontsize: 30,
        },
    });

格式2:值是对象变量名,对象在data中进行声明

<div id="app">
    <div v-bind:style="styleObject">西部数据</div>
</div>
<script>
    let vm = new Vue({
        el: '#app',
        data: {
            styleObject: {
                color: 'red',
                fontsize: '30px',
            }
        },
    });
</script>

格式3:值是一个数组

<div id="app">
    <div v-bind:style="[style1,style2]">o(* ̄︶ ̄*)o</div>
</div>
<script>
    let vm = new Vue({
        el: '#app',
        data: {
            style1: {
                color: 'red',
            },
            style2: {
                background: 'yellow',
                fontsize: '20px',
            },
        },
    });
</script>

2.3.3 vue实例--选项卡

    <script src="vue.min.js"></script>
    <style>
        #card {
             500px;
            height: 350px;
        }

        .title {
            height: 50px;
        }

        .title span {
             100px;
            height: 50px;
            background-color: #ccc;
            display: inline-block;
            line-height: 50px; /* 设置行和当前元素的高度相等,就可以让文本内容上下居中 */
            text-align: center;
        }

        .content .list {
             500px;
            height: 300px;
            background-color: yellow;
            display: none;
        }

        .content .active {
            display: block;
        }

        .title .current {
            background-color: yellow;
        }
    </style>
</head>
<body>
<div id="card">
    <div class="title">
        <span :class="num==0?'current':''" @click="num=0">国内新闻</span>
        <span :class="num==1?'current':''" @click="num=1">国际新闻</span>
        <span :class="num==2?'current':''" @click="num=2">银河新闻</span>
    </div>
    <div class="content">
        <div class="list" :class="num==0?'active':''" @click="num=0">国内新闻列表</div>
        <div class="list" :class="num==1?'active':''" @click="num=1">国际新闻列表</div>
        <div class="list" :class="num==2?'active':''" @click="num=2">银河新闻列表</div>
    </div>
</div>
<script>
    let card = new Vue({
        el: "#card",
        data: {
            num: 0,
        },
    });

</script>

2.4 条件渲染指令

vue中提供了两个指令可以用于判断是否要显示元素,分别是v-if和v-show。

2.4.1 v-if

vue对象会把条件的结果变成布尔值

<div id="test">
    <h1 v-if="yes" @click="yes=!yes">yes</h1>
</div>
<script>
    let vm = new Vue({
        el:'#test',
        data:{
            yes:true, //true是显示,flase是隐藏
        },
    });
</script>

隐藏:
通过dom操作将标签给删除,绑定点击事件,点完一次隐藏后,再点一次标签并不会出现,因为标签已被删除了。

2.4.2 v-else

v-else指令来表示 v-if 的“else 块”,v-else 元素必须紧跟在带 v-if 或者 v-else-if 的元素的后面,否则它将不会被识别。且只能有一个v-else

<div id="test">
    <h1 v-if="yes">yes</h1>
    <h1 v-else>no</h1>
</div>
<script>
    let vm = new Vue({
        el: '#test',
        data: {
            yes: false,
        },
    });
</script>

2.4.3 v-else-if

用法和v-if大致一样,区别在于2点:

  • v-show后面不能v-else或者v-else-if;

  • v-show隐藏元素时,使用的是display:none来隐藏的,而v-if是直接从HTML文档中移除元素[ DOM操作中的remove ]

<div id="test">
    <h1 v-show="yes" @click="yes=!yes">yes</h1>
</div>
<script>
    let vm = new Vue({
        el:'#test',
        data:{
            yes:false, //true是显示,flase是隐藏
        },
    });
</script>

2.5列表渲染指令

在vue中,可以通过v-for指令可以将一组数据渲染到页面中,数据可以是数组或者对象

#数据是数组
<div id="app">
    <ul>
        <li v-for="book in book_list">{{ book.title }}</li>
    </ul>
    <ul>
        <!--i是列表的每一个元素,j是每个元素的下标-->
        <li v-for="(book, index) in book_list">第{{ index+1}}本图书:{{book.title}}</li>
    </ul>
</div>
<script>
    let vm = new Vue({
        el: "#app",
        data: {
            book_list: [
                {"id": 1, "title": "图书名称1", "price": 200},
                {"id": 2, "title": "图书名称2", "price": 200},
                {"id": 3, "title": "图书名称3", "price": 200},
                {"id": 4, "title": "图书名称4", "price": 200},
            ]
        }
    });
</script>

# 数据是对象:
 <ul>
            <!--i是每一个value值-->
            <li v-for="value in book">{{value}}</li>
        </ul>
        <ul>
            <!--i是每一个value值,j是每一个键名-->
            <li v-for="attr, value in book">{{attr}}:{{value}}</li>
        </ul>
        <script>
            var vm1 = new Vue({
                el:"#app",
                data:{
                    book: {
                        // "attr":"value"
                        "id":11,
                        "title":"图书名称1",
                        "price":200
                    },
                },
            })
        </script>
原文地址:https://www.cnblogs.com/surpass123/p/13144337.html