1 Star 0 Fork 165

ElonChung / Java-Review

forked from flatfish / Java-Review 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
Vue-第1篇-基础学习.md 28.41 KB
一键复制 编辑 原始数据 按行查看 历史
icanci 提交于 2020-09-13 13:38 . :fire:更新Vue文件

Vue-第1篇-基础学习

概述

  • 官网: https://cn.vuejs.org/
  • 动态构建用户界面
  • Soc原则:关注点分离原则
  • 视图层:HTML+CSS+JavaScript 给用户看,刷新后台给的数据
  • 网络通信:axios
  • 页面跳转:Vue-router
  • 状态管理:Vuex
  • Vue-UI:ICE

特点

  • 遵循MVVM模式
  • 编码简洁,体积小,运行效率高,适合移动/PC端开发
  • 它本身只关注UI,可以轻松引入Vue插件或者其他第三方库开发项目

与其他前端JS框架的关联

  • 借鉴 angular 的 模板数据绑定技术
  • 借鉴 react 的组件化虚拟DOM技术

Vue扩展插件

  • vue-cli:脚手架
  • vue-resource(axios):ajax请求
  • vue-router:路由
  • vuex:状态管理
  • vue-lazyload:图片懒加载
  • vue-scroller:页面滑动相关
  • mint-ui:基于Vue的UI组件库(移动端)
  • element-ui:基于Vue的UI组件库(PC端)

Vue的环境搭建

第一个Vue程序

  • 注意:其实Vue官网已经给了很优秀的实例,可以按照Vue官网给出的Demo学习

  • 理解MVVM

    • Model:模型,数据对象
    • View:视图,模板页面
    • ViewMolel:视图模型(Vue的实例)
  • 引入Vue.js

  • 创建Vue对象

    • el:指定根element(选择器)
    • data:初始化数据(页面可以访问)
  • 双向数据绑定:v-model

  • 显示数据:{{message}}

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
    </head>
    <body>
        <div id="app">
            <input type="text" v-model="message"/>
            <p>Hello {{message}}</p>
        </div>
        <script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
        <script type="text/javascript">
            // 创建 Vue 实例
            var app = new Vue({
                // 配置对象
                // 选择器
                el: "#app",
                // 数据
                data: {
                    message: 'hello vue'
                }
            })
        </script>
    </body>
</html>

模板语法

  • 模板的理解
    • 动态的html页面
    • 包含了一些JS语法代码
      • 双大括号表达式
      • 指令(以 v- 开头的自定义标签属性)
  • 双大括号表达式
    • 语法:{{exp}} 或者 {{{exp}}}
    • 功能:可以向页面输出数据
    • 可以调用对象的方法
  • 指令一:强制数据绑定
    • 功能:指定变化的属性值
    • 完整写法
      • v-bind:xxx='yyy' // yyy 会作为表达式解析执行
    • 简洁写法
      • :xxx='yyy'
  • 指令二:绑定事件监听
    • 功能:绑定指定事件名的回调函数
    • 完整写法
      • v-on:click='xxx'
    • 简洁写法
      • @click='xxx'
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
    </head>
    <body>
        <div id="app">
            <h3>1.使用大括号表达式</h3>
            {{message.toUpperCase()}}
            <h3>2.指令一:强制数据绑定</h3>
            <img v-bind:src="imgUrl">
            <img :src="imgUrl">
            <h3>3.指令二:绑定事件监听</h3>
            <button v-on:click="test">test</button>
            <button @click="test">test</button>
            <button @click="test2(' zeze')">test2</button>
        </div>
        <script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
        <script type="text/javascript">
            // 创建 Vue 实例
            var app = new Vue({
                // 配置对象
                // 选择器
                el: "#app",
                // 数据
                data: {
                    message: 'hello vue',
                    imgUrl: 'https://exception-image-bucket.oss-cn-hangzhou.aliyuncs.com/158719311614664'
                },
                methods: {
                    test() {
                        alert("hehhe")
                    },
                    test2(obj) {
                        alert("hehhe" + obj)
                    }
                }
            })
        </script>
    </body>
</html>

计算属性和监视

  • 计算属性
    • 在Computer属性对象中定义计算属性的方法
    • 在页面中使用{{方法名}}来显示计算的结果
  • 监视属性
    • 通过 vm 对象的 $watch( ) 或者 watch 配置来监视指定的属性
    • 当属性变化的时候,回调函数自动调用,在函数内部进行计算
  • 计算属性高级
    • 通过 getter/setter 实现对属性数据的显示和监视
    • 计算属性存在缓存,多次读取只执行一次 getter 计算
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<div id="app">
			姓:<input type="text" placeholder="first name" v-model="firstName"> <br>
			名:<input type="text" placeholder="last name" v-model="lastName"> <br>
			姓名1(单向):<input type="text" placeholder="full name 1" v-model="fullName1"> <br>
			姓名2(单向):<input type="text" placeholder="full name 2" v-model="fullName2"> <br>
			姓名3(双向):<input type="text" placeholder="full name 3" v-model="fullName3"> <br>
			<p>{{fullName1}}</p>
			<p>{{fullName2}}</p>
			<p>{{fullName3}}</p>
		</div>
		<script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
		<script type="text/javascript">
			// 创建 Vue 实例
			var app = new Vue({
				// 配置对象
				// 选择器
				el: "#app",
				// 数据
				data: {
					firstName: 'A',
					lastName: 'B'
					// fullName1: 'A B'
				},
				computed: {
					// 什么时候执行,初始化的时候执行/相关的data属性数据发送改变
					fullName1() {
						// 计算属性的方法,
						console.log('fullName1()')
						return this.firstName + ' ' + this.lastName
					},
					fullName3: {
						// 什么是回调函数
						// 1.你定义的
						// 2.你没有调用
						// 3.但是它最后执行了
						// 什么时候调用回调函数,用来做什么
						// 回调函数,当需要读取当前属性值的时候,根据相关的数据计算并返回当前属性的值
						// 
						get(){
							return this.firstName + ' ' + this.lastName
						},
						// 当属性值发生改变的时候调用,更新相关的属性数据
						set(value){
							// value 就是fullName3 的最新的是
							const names = value.split(' ')
							this.firstName = names[0]
							this.lastName = names[1]
						}
					}
				},
				watch: {
					// 配置监视
					firstName: function(value) {
						// first name发生了改变
						console.log(this)
						this.fullName2 = value + ' ' + this.lastName
					}
				}
			})

			app.$watch('lastName', function(value) {
				// 更新 fullName2
				this.fullName2 = this.firstName + ' ' + value
			})
		</script>
	</body>
</html>

强制绑定class和style

  • 在应用界面中,某个(些)元素的样式是变化的
  • class/style 绑定就是专门用来实现动态样式效果的技术
  • class动态绑定: :class='xxx'
    • xxx 是字符串
    • xxx 是对象
    • xxx 是数组
  • style 绑定
    • :style="{color:activeColor,fontSize:fontSize+'px'}"
    • 其中 activeColor/fontSize 是 data属性
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			.aClass {
				color: red;
			}

			.bClass {
				color: blue;
			}

			.cClass {
				font-size: 20px;
			}
		</style>
	</head>
	<body>
		<div id="app">
			<h4>1.class 绑定: :class='xxx'</h4>
			<p class="cClass" :class="a">:class='xxx'是字符串</p>
			<p :class="{aClass: isA,bClass:isB}">:class='xxx'是对象</p>
			<p :class="['aClass','bClass']">:class='xxx'是数组</p>
			<h4>2.style绑定</h4>
			<p :style="{color:activeColor,fontSize:fontSize+'px'}">style绑定</p>
			<button @click="update" type="button">按钮</button>
		</div>
		<script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
		<script type="text/javascript">
			// 创建 Vue 实例
			var app = new Vue({
				// 配置对象
				// 选择器
				el: "#app",
				// 数据
				data: {
					a: 'aClass',
					isA: true,
					isB: false,
					activeColor: 'red',
					fontSize: 20
				},
				methods: {
					update() {
						this.a = 'bClass',
						this.isA = false,
						this.isB = true,
						this.activeColor = 'green',
						this.fontSize = 40
					}
				}
			})
		</script>
	</body>
</html>

条件渲染

  • 条件渲染指令
    • v-if
    • v-else
    • v-show
  • 比较 v-if 与 v-show
    • 如果需要频繁切换,v-show比较好
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<div id="app">
			<p v-if="ok">成功了</p>
			<p v-else>失败了</p>
			<p v-show="ok">表白成功</p>
			<p v-show="!ok">表白失败</p>
			<button @click="ok=!ok" type="button">切换</button>
		</div>
		<script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
		<script type="text/javascript">
			// 创建 Vue 实例
			var app = new Vue({
				// 配置对象
				// 选择器
				el: "#app",
				// 数据
				data: {
					ok: true
				}
			})
		</script>
	</body>
</html>

列表渲染

  • 列表显示
  • v-for 遍历数组
  • v-for 遍历对象
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<div id="app">
			<h3>测试:v-for 遍历数组</h3>
			<ul>
				<li v-for="(p,index) in persons" :key="index">
					{{index}} == {{p.name}} == {{p.age}}
					<button type="button" @click="deleteP(index)">删除</button>
					<button type="button" @click="updateP(index,{name:'Var',age:10})">更新</button>
				</li>
			</ul>
			<h3>测试:v-for 遍历对象</h3>
			<ul>
				<li v-for="(value,key) in persons[1]">
					{{value}} == {{key}}
				</li>
			</ul>
		</div>
		<script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
		<script type="text/javascript">
			// 创建 Vue 实例
			var app = new Vue({
				// 配置对象
				// 选择器
				el: "#app",
				// 数据
				data: {
					// vue 本身只是监视了 persons 的改变,没有监视数组内容的改变、
					// vue 重写了数组中的一系列改变数组的内部结构数据 (先调用原生,更新界面)
					// 数组内部改变,界面自动刷新
					persons: [{
							name: 'tom1',
							age: 17
						},
						{
							name: 'tom2',
							age: 18
						},
						{
							name: 'tom3',
							age: 15
						},
						{
							name: 'tom4',
							age: 110
						},
						{
							name: 'tom5',
							age: 19
						},
						{
							name: 'tom6',
							age: 17
						}
					]
				},
				methods: {
					deleteP(index) {
						// 删除persons中指定index的p
						this.persons.splice(index, 1)
					},
					updateP(index, p) {
						// this.persons[index] = p 这操作并没有改变 persons 本身 没有调用变异方法
						this.persons.splice(index, 1, p); // 这样是可以的
						this.persons[index].name = p.name;
						this.persons[index].age = p.age;
					}
				}
			})
		</script>
	</body>
</html>

列表的搜索和排序

  • 列表过滤
  • 列表排序
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<div id="app">
			<input type="text" v-model="searchName" />
			<ul>
				<li v-for="(p,index) in filterPersons">
					{{index}} == {{p.name}} == {{p.age}}
				</li>
			</ul>
			<button type="button" @click="setOrderType(1)">年龄升序</button>
			<button type="button" @click="setOrderType(2)">年龄降序</button>
			<button type="button" @click="setOrderType(0)">原本排序</button>
		</div>
		<script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
		<script type="text/javascript">
			// 创建 Vue 实例
			var app = new Vue({
				// 配置对象
				// 选择器
				el: "#app",
				// 数据
				data: {
					// 0 为原本信息
					// 1 升序
					// 2 降序
					orderType: 0,
					persons: [{
							name: 'tom1',
							age: 17
						},
						{
							name: 'tom2',
							age: 18
						},
						{
							name: 'tom3',
							age: 15
						},
						{
							name: 'tom4',
							age: 110
						},
						{
							name: 'tom5',
							age: 19
						},
						{
							name: 'tom6',
							age: 17
						}
					],
					searchName: ''
				},
				computed: {
					filterPersons() {
						// 取出相关的数据
						const {
							searchName,
							persons,
							orderType
						} = this
						// 最终需要显示的数组
						let fPersons;
						// 队persons进行过滤
						fPersons = persons.filter(p => p.name.indexOf(searchName) >= 0)
						// 排序
						if(orderType !==0){
							fPersons.sort(function(p1,p2){
								// 1 为升序 
								// 2 为降序
								// 返回负数,p1在前,返回正数,p2在前
								if(orderType===2){
									return p2.age - p1.age
								}else{
									return - (p2.age - p1.age)
								}
							})
						}
						return fPersons
					}
				},
				methods:{
					setOrderType(orderType){
						this.orderType = orderType
					}
				}
			})
		</script>
	</body>
</html>

事件处理

  • 绑定监听
    • 默认带有event事件
  • 事件修饰符
    • 停止事件冒泡
    • 阻止事件的默认行为
  • 按键修饰符
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<div id="app">
			<h3>1.绑定监听</h3>
			<button v-on:click="test1" type="button">test1</button>
			<button @click="test2('ic')" type="button">test2</button>
			<button @click="test3($event)" type="button">test3</button>
			<!-- 也可以这样传参  test4(123,$event)-->
			<button @click="test4(123)" type="button">test4</button>
			<h3>2.事件修饰符</h3>
			<div style="width: 200px; height: 200px; background-color: red;" @click="test5()">
				<!-- 需要停止事件冒泡 -->
				<div style="width: 100px; height: 100px; background-color: lawngreen;" @click.stop="test6()">
				</div>
			</div>
			<!-- 阻止事件的默认行为 -->
			<a href="http://www.baidu.com" @click.prevent="test7()">去百度</a>
			<h3>3.按键修饰符</h3>
			<input type="text" @keyup.13="test8()" />
			<input type="text" @keyup.enter="test8()" />
			<input type="text" @keyup.a="test8()" />
		</div>
		<script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
		<script type="text/javascript">
			// 创建 Vue 实例
			var app = new Vue({
				// 配置对象
				// 选择器
				el: "#app",
				// 数据
				data: {
					message: 'hello vue'
				},
				methods: {
					test1() {
						alert("hello")
					},
					test2(value) {
						alert("hello" + value)
					},
					test3(event) {
						alert(event.target.innerHTML)
					},
					test4(number) {
						// event 默认就有这个对象
						alert(event.target.innerHTML)
						alert(number)
					},
					test5() {
						alert('5')
					},
					test6() {
						// event.stopPropagation()

						alert('6')
					},
					test7(){
						// event.preventDefault()
						alert("7")
					},
					test8(){
						// if(event.keyCode==13){
							alert(event.target.value)
						// }
					
					}
				}
			})
		</script>
	</body>
</html>

表单输入的绑定

  • 使用 v-model (双向数据绑定) 自动收集数据
  • text/textarea
  • checkbox
  • radio
  • select
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<div id="app">

			<form action="/xxx" @submit.prevent="handleSubmit">
				<span>用户名: </span>
				<input type="text" v-model="username"><br>

				<span>密码: </span>
				<input type="password" v-model="pwd"><br>

				<span>性别: </span>
				<input type="radio" id="female" value="女" v-model="sex">
				<label for="female"></label>
				<input type="radio" id="male" value="男" v-model="sex">
				<label for="male"></label><br>

				<span>爱好: </span>
				<input type="checkbox" id="basket" value="basket" v-model="likes">
				<label for="basket">篮球</label>
				<input type="checkbox" id="foot" value="foot" v-model="likes">
				<label for="foot">足球</label>
				<input type="checkbox" id="pingpang" value="pingpang" v-model="likes">
				<label for="pingpang">乒乓</label><br>

				<span>城市: </span>
				<select v-model="cityId">
					<option value="">未选择</option>
					<option :value="city.id" v-for="(city, index) in allCitys" :key="city.id">{{city.name}}</option>
				</select><br>
				<span>介绍: </span>
				<textarea rows="10" v-model="info"></textarea><br><br>

				<input type="submit" value="注册">
			</form>

		</div>
		<script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
		<script type="text/javascript">
			// 创建 Vue 实例
			new Vue({
				el: '#app',
				data: {
					username: '',
					pwd: '',
					sex: '',
					likes: ['foot'],
					allCitys: [{
						id: 1,
						name: 'BJ'
					}, {
						id: 2,
						name: 'SS'
					}, {
						id: 3,
						name: 'SZ'
					}],
					cityId: '2',
					info: ''
				},
				methods: {
					handleSubmit() {
						console.log(this.username, this.pwd, this.sex, this.likes, this.cityId, this.info)
						alert('提交注册的ajax请求')
					}
				}
			})
		</script>
	</body>
</html>

Vue的生命周期

  • vue对象的生命周期
    • 初始化显示
    • beforeCreate()
    • created()
    • beforeMount()
    • mounted()
    • 更新状态
    • beforeUpdate()
    • updated()
    • 销毁vue实例: vm.$destory()
    • beforeDestory()
    • destoryed()
    • 常用的生命周期方法
      • created()/mounted(): 发送ajax请求, 启动定时器等异步任务
      • beforeDestory(): 做收尾工作, 如: 清除定时器
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <div id="test">
            <button @click="destroyVue">destory vue</button>
            <p v-if="isShow">ic</p>
        </div>

        <script type="text/javascript" src="js/vue.js"></script>
        <script type="text/javascript">
            new Vue({
                el: '#test',
                data: {
                    isShow: true
                },

                mounted() {
                    // 执行异步任务
                    // 初始化之后立即调用
                    this.intervalId = setInterval(() => {
                        console.log('-----')
                        this.isShow = !this.isShow
                    }, 1000)
                },

                beforeDestroy() {
                    // 死之前调用
                    console.log('beforeDestroy()')
                    // 执行收尾的工作
                    clearInterval(this.intervalId)
                },

                methods: {
                    destroyVue() {
                        this.$destroy()
                    }
                }
            })
        </script>
    </body>
</html>
<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		<div id="test">
			<button @click="destroyVue">destory vue</button>
			<p v-if="isShow">IC</p>
		</div>
		<script type="text/javascript" src="./js/vue.js"></script>
		<script type="text/javascript">
			new Vue({
				el: '#test',
				data: {
					isShow: true
				},
                // 创建阶段
				beforeCreate() {
					console.log('beforeCreate()')
				},
                // 创建
				created() {
					console.log('created()')
				},
				beforeMount() {
					console.log('beforeMount()')
				},
				mounted() {
					console.log('mounted()')
					// 执行异步任务
					this.intervalId = setInterval(() => {
						console.log('-----')
						this.isShow = !this.isShow
					}, 1000)
				},
                // 更新阶段
				beforeUpdate() {
					console.log('beforeUpdate()')
				},
                // 更新
				updated() {
					console.log('updated()')
				},
                // 销毁阶段
				beforeDestroy() {
					console.log('beforeDestroy()')
					// 执行收尾的工作
					clearInterval(this.intervalId)
				},
                // 销毁
				destroyed() {
					console.log('destroyed()')
				},
				methods: {
					destroyVue() {
						this.$destroy()
					}
				}
			})
		</script>
	</body>
</html>

过度&动画

  • Vue动画的理解
    • 操作CSS的 transition或者 animation
    • Vue会给目标元素添加 / 移除特定的class
    • 过度的相关类名
      • xxx-enter-active:指定显示的 transition
      • xxx-leave-active:指定隐藏的 transition
      • xxx-enter/xxx-leave-to:指定隐藏时候的样式
<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style>
			/*指定过渡样式*/
    .xxx-enter-active, .xxx-leave-active {
      transition: opacity 1s
    }
    /*指定隐藏时的样式*/
    .xxx-enter, .xxx-leave-to {
      opacity: 0;
    }


    .move-enter-active {
      transition: all 1s
    }

    .move-leave-active {
      transition: all 3s
    }

    .move-enter, .move-leave-to {
      opacity: 0;
      transform: translateX(20px)
    }
  </style>
	</head>
	<body>
		<div id="demo">
			<button @click="show = !show">Toggle</button>
			<transition name="xxx">
				<p v-show="show">hello</p>
			</transition>
		</div>

		<hr>
		<div id="demo2">
			<button @click="show = !show">Toggle2</button>
			<transition name="move">
				<p v-show="show">hello</p>
			</transition>
		</div>


		<script type="text/javascript" src="js/vue.js"></script>
		<script type="text/javascript">
			new Vue({
				el: '#demo',
				data: {
					show: true
				}
			})

			new Vue({
				el: '#demo2',
				data: {
					show: true
				}
			})
		</script>
	</body>
</html>
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style>
            .bounce-enter-active {
                animation: bounce-in .5s;
            }
            .bounce-leave-active {			
                animation: bounce-in .5s reverse;
            }
            @keyframes bounce-in {
                0% {
                    transform: scale(0);
                }
                50% {
                    transform: scale(1.5);
                }
                100% {
                    transform: scale(1);
                }
            }
        </style>
    </head>
    <body>

        <div id="example-2">
            <button @click="show = !show">Toggle show</button>
            <br>
            <transition name="bounce">
                <p v-if="show" style="display: inline-block">Lorem</p>
            </transition>
        </div>

        <script type="text/javascript" src="js/vue.js"></script>
        <script>
            new Vue({
                el: '#example-2',
                data: {
                    show: true
                }
            })
        </script>
    </body>
</html>

过滤器

  • 理解过滤器

    • 功能: 对要显示的数据进行特定格式化后再显示
    • 注意: 并没有改变原本的数据, 可是产生新的对应的数据
  • 编码

  • 定义过滤器

Vue.filter(filterName, function(value[,arg1,arg2,...]){
// 进行一定的数据处理
return newValue
})
  • 使用过滤器
<div>{{myData | filterName}}</div>
<div>{{myData | filterName(arg)}}</div>
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>11_过滤器</title>
    </head>
    <body>
        <!--需求: 对当前时间进行指定格式显示-->
        <div id="test">
            <h2>显示格式化的日期时间</h2>
            <p>{{time}}</p>
            <p>最完整的: {{time | dateString}}</p>
            <p>年月日: {{time | dateString('YYYY-MM-DD')}}</p>
        </div>

        <script type="text/javascript" src="js/vue.js"></script>
        <script type="text/javascript" src="https://cdn.bootcss.com/moment.js/2.22.1/moment.js"></script>
        <script>
            // 定义过滤器
            Vue.filter('dateString', function(value, format = 'YYYY-MM-DD HH:mm:ss') {
                return moment(value).format(format);
            })
            new Vue({
                el: '#test',
                data: {
                    time: new Date()
                },
                mounted() {
                    setInterval(() => {
                        this.time = new Date()
                    }, 1000)
                }
            })
        </script>
    </body>
</html>

Vue指令

  • 常用内置指令

  • v-text:更新元素的 textContent

  • v-html:更新元素的 innerHTML

  • v-if:如果为true,当前标签才会输出到页面

  • v-else:如果为false,当前标签才会输出到页面

  • v-show:通过控制 display 样式来控制显示/隐藏

  • v-for:遍历数组/对象

  • v-on:绑定事件监听,一般简写为@

  • v-bind:强制绑定解析表达式,可以省略 v-bind

  • v-model:双向数据绑定

  • ref:指定唯一标识,vue对象通过 $els 属性访问这个元素对象

  • v-cloak:防止闪现,与css配合:[v-cloak]{dispaly:none}

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style>
			/* 属性选择器 */
			[v-cloak] { display: none }
		</style>
	</head>
	<body>
		<div id="example">
			<p v-cloak>{{content}}</p>
			<p v-text="content"></p>
			<!--p.textContent = content-->
			<p v-html="content"></p>
			<!--p.innerHTML = content-->
			<p ref="msg">abcd</p>
			<button @click="hint">提示</button>
		</div>

		<script type="text/javascript" src="js/vue.js"></script>
		<script type="text/javascript">
			new Vue({
				el: '#example',
				data: {
					content: '<a href="http://www.baidu.com">百度一下</a>'
				},
				methods: {
					hint() {
						alert(this.$refs.msg.innerHTML)
					}
				}
			})
		</script>
	</body>
</html>
  • 自定义内置指令
<!--
1. 注册全局指令
  Vue.directive('my-directive', function(el, binding){
    el.innerHTML = binding.value.toupperCase()
  })
2. 注册局部指令
  directives : {
    'my-directive' : {
        bind (el, binding) {
          el.innerHTML = binding.value.toupperCase()
        }
    }
  }
3. 使用指令
  v-my-directive='xxx'
-->
<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>

		<!--
		需求: 自定义2个指令
		1. 功能类型于v-text, 但转换为全大写
		2. 功能类型于v-text, 但转换为全小写
		-->

		<div id="test">
			<p v-upper-text="msg"></p>
			<p v-lower-text="msg"></p>
		</div>

		<div id="test2">
			<p v-upper-text="msg"></p>
			<p v-lower-text="msg"></p>
		</div>

		<script type="text/javascript" src="js/vue.js"></script>
		<script type="text/javascript">
			// 注册一个全局指令
			// el: 指令所在的标签对象
			// binding: 包含指令相关数据的容器对象
			Vue.directive('upper-text', function(el, binding) {
				console.log(el, binding)
				el.textContent = binding.value.toUpperCase()
			})
			new Vue({
				el: '#test',
				data: {
					msg: "I Like You"
				},
				// 注册局部指令
				// 只在当前Vue的作用范围下有效
				directives: {
					'lower-text'(el, binding) {
						console.log(el, binding)
						el.textContent = binding.value.toLowerCase()
					}
				}

			})

			new Vue({
				el: '#test2',
				data: {
					msg: "I Like You Too"
				}
			})
		</script>
	</body>
</html>

Vue插件

(function (window) {
    // 需要向外暴漏的插件对象
    const MyPlugin = {}
    MyPlugin.install = function (Vue, options) {
        // 1. 添加全局方法或属性
        Vue.myGlobalMethod = function () {
            console.log('Vue函数对象的myGlobalMethod()')
        }

        // 2. 添加全局资源
        // 自定义指令
        Vue.directive('my-directive',function (el, binding) {
            el.textContent = 'my-directive----'+binding.value
        })

        // 4. 添加实例方法
        Vue.prototype.$myMethod = function () {
            console.log('vm $myMethod()')
        }
    }
    window.MyPlugin = MyPlugin
})(window)
<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>

		<div id="test">
			<p v-my-directive="msg"></p>
		</div>

		<script type="text/javascript" src="js/vue.js"></script>
		<script type="text/javascript" src="vue-myPlugin.js"></script>
		<script type="text/javascript">
			// 声明使用插件(安装插件: 调用插件的install())
			Vue.use(MyPlugin) // 内部会调用插件对象的install()

			const vm = new Vue({
				el: '#test',
				data: {
					msg: 'HaHa'
				}
			})
			Vue.myGlobalMethod()
			vm.$myMethod()

			new Object()
		</script>
	</body>
</html>
1
https://gitee.com/elonchung/Java-Review.git
git@gitee.com:elonchung/Java-Review.git
elonchung
Java-Review
Java-Review
master

搜索帮助