Vue的模板语法(续集)

本文详细介绍了Vue.js中的事件处理器,包括事件修饰符如.stop、.prevent等,以及按键修饰符。接着探讨了自定义组件的创建、注册和使用props进行数据传递。最后,讲解了组件间的通信方式,如通过$on和$emit实现父子组件间的交互。文中通过实例代码加深理解,展示了如何在实际应用中运用这些概念。
摘要由CSDN通过智能技术生成

前言

接上篇文章,上篇文章分享了Vue的模板语法的 插值、指令、过滤器、计算属性以及监听器。本篇文章要分享的内容为 事件处理器、自定义组件以及组件通信。


一、事件处理器

事件监听可以使用v-on 指令 ## 之前已学习

  

事件修饰符

  Vue通过由点(.)表示的指令后缀来调用修饰符,

  .stop

  .prevent

  .capture

  .self

  .once

按键修饰符

  Vue允许为v-on在监听键盘事件时添加按键修饰符:

  <!-- 只有在 keyCode 是 13 时调用 vm.submit() -->

  <input v-on:keyup.13="submit">

  Vue为最常用的按键提供了别名

  <!-- 同上 -->

  <input v-on:keyup.enter="submit">

  全部的按键别名:

  .enter

  .tab

  .delete (捕获 "删除" 和 "退格" 键)

  .esc

  .space

  .up

  .down

  .left

  .right

  .ctrl

  .alt

  .shift

  .meta      

 注1:什么是事件冒泡?

 

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.0/vue.js"></script>
		<style>
			.red {
				width: 400px;
				height: 400px;
				background-color: red;
			}

			.yellow {
				width: 300px;
				height: 300px;
				background-color: yellow;
			}

			.blue {
				width: 200px;
				height: 200px;
				background-color: blue;
			}

			.green {
				width: 100px;
				height: 100px;
				background-color: green;
			}
		</style>
	</head>
	<body>
		<div id="app">
			<p>冒泡事件</p>
			<div class="red" @click="red">
				<div class="yellow" @click.stop="yellow">
					<div class="blue" @click.stop="blue">
						<div class="green" @click.stop="green">

						</div>
					</div>
				</div>
			</div>
			
			<p>提交答案</p>
			<input type="button" value="提交" @click.once="answer"/>
			
			<p>按键修饰符</p>
			<input @keyup.enter="answer" />
		</div>
	</body>
	<script>
		new Vue({
			el: '#app',
			methods: {
				red() {
					alert('red');
				},
				yellow() {
					alert('yellow');
				},
				blue() {
					alert('blue');
				},
				green() {
					alert('green');
				},
				answer(){
					alert('已完成,提交答案');
					console.log('已提交')
				}
			}
		})
	</script>
</html>

         冒泡事件

        事件修饰符:once

 

        按键修饰符:enter,对于按键修饰符没有进行事件修饰,所以可以多次使用。

 

 

 

二、自定义组件

         组件(Component)是Vue最强大的功能之一

      组件可以扩展HTML元素,封装可重用的代码

      组件系统让我们可以用独立可复用的小组件来构建大型应用,几乎任意类型的应用的界面都可以抽象为一个组件树

 

全局和局部组件

      全局组件:Vue.component(tagName, options),tagName为组件名,options为配置选项。

      局部组件: new Vue({el:'#d1',components:{...}})

      注册后,我们可以使用以下方式来调用组件:

      <tagName></tagName>

 props

      props是父组件用来传递数据的一个自定义属性。

      父组件的数据需要通过props把数据传给子组件,子组件需要显式地用props选项声明 "prop"

 

 

 注1:因为组件是可复用的 Vue 实例,所以它们与 new Vue 接收相同的选项,例如 data、computed、watch、methods

        以及生命周期钩子等。仅有的例外是像el这样根实例特有的选项。

   注2:当我们定义这个 <button-counter> 组件时,你可能会发现它的data并不是像这样直接提供一个对象

        data: {

          count: 0

        }

        取而代之的是,一个组件的data选项必须是一个函数,因此每个实例可以维护一份被返回对象的独立的拷贝:

        data: function () {

          return {

            count: 0

          }

        }

  

    注3:定义组件名的方式有两种

         短横线分隔命名(建议使用)

         Vue.component('my-component-name', { /* ... */ }),引用方式:<my-component-name>

         首字母大写命名

         Vue.component('MyComponentName', { /* ... */ }),引用方式: <my-component-name>和<MyComponentName>都是可接受的   

    注4:HTML 中的特性名是大小写不敏感的,所以浏览器会把所有大写字符解释为小写字符。这意味着当你使用 DOM 中的模板时,

         camelCase (驼峰命名法) 的 prop 名需要使用其等价的 kebab-case (短横线分隔命名) 命名:

         props: ['postTitle'],<my-tag post-title="hello!"></my-tag>

    注5:props: ['title', 'likes', 'isPublished', 'commentIds', 'author']

         希望每个 prop 都有指定的值类型

         props: {

           title: String,

           likes: Number,

           isPublished: Boolean,

           commentIds: Array,

           author: Object,

           callback: Function,

           contactsPromise: Promise // or any other constructor

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.0/vue.js"></script>
	</head>
	<body>
		<div id="app">
			<my-button m="老六"></my-button>
		</div>
	</body>
	<script>
		Vue.component('my-button', {
			// props是定义组件中的变量的
			props: ['m'],
			// template代表了自定义组件在页面上显示的类容
			template: '<button v-on:click="incrn">我被{{m}}点击{{n}}次</button>',
			data: function() {
				return {
					n: 1
				}
			},
			methods: {
				incrn() {
					this.n++;
				}
			}
		});
		// 绑定边界	ES6具体体现
		new Vue({
			el: '#app',
			data() {
				return {};
			}
		})
	</script>
</html>

 

三、组件通信

监听事件:$on(eventName)

   触发事件:$emit(eventName)

   注1:Vue自定义事件是为组件间通信设计   

        vue中父组件通过prop传递数据给子组件,而想要将子组件的数据传递给父组件,则可以通过自定义事件的绑定

     

        父Vue实例->Vue实例,通过prop传递数据

        子Vue实例->父Vue实例,通过事件传递数据

   注2:事件名

        不同于组件和prop,事件名不存在任何自动化的大小写转换。而是触发的事件名需要完全匹配监听这个事件所用的名称

        建议使用“短横线分隔命名”,例如:three-click

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.0/vue.js"></script>
	</head>
	<body>
		<div id='app'>
			<ul>
				<li>
					<h3>{{ts}}</h3>
					<p>vue组件</p>
					<my-button m="老六" v-on:three-click="xxx"></my-button>
				</li>
			</ul>
		</div>
	</body>
	<script>
		Vue.component('my-button', {
			props: ['m'],
			template: '<button v-on:click="doClickMyButton">我是一个自定义组件,被{{m}}点了{{n}}次</button>',
			data: function() {
				return {
					n: 0
				};
			},
			methods: {
				doClickMyButton: function() {
					console.log('doClickMyButton方法被调用');
					this.n++;
					if (this.n % 3 == 0) {
						// 触发自定义组件定义的事件,这里可以传递任意个参数
						// 但是触发的事件绑定的函数要与参数个数一致
						this.$emit('three-click', this.n, '666', '真的老六');
					}
				}
			}
		})
		new Vue({
			el: '#app',
			data: {
				ts: new Date().getTime()
			},
			methods: {
				xxx: function(a, b, c) {
					console.log("自定义事件绑定的函数被执行...")
					console.log(a);
					console.log(b);
					console.log(c);
				}
			}
		})
	</script>
</html>

 

 

四、案例

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.0/vue.js"></script>
	</head>
	<body>
		<div id="app">
			<ul>
				<li>
					<p>vue表单</p>
					<label>姓名:</label><input v-model="uname" /><br />
					<label>密码:</label><input v-model="upwd" type="password" /><br />
					<!-- 将用户的输入值转为 Number 类型 -->
					<label>年龄:</label><input v-model.number="age" /><br />
					<label>性别:</label>
					<input type="radio" v-model="sex" name="sex" value="1" />男
					<input type="radio" v-model="sex" name="sex" value="0" />女<br />
					<label>爱好:</label>
					<div v-for="h in hobby">
						<input type="checkbox" v-model="hobbies" v-bind:value="h.id" />{{h.name}}
					</div>
					<label>类别:</label>
					<select v-model="type">
						<option value="-1">===请选择===</option>
						<option v-for="t in types" v-bind:value="t.id">{{t.name}}</option>
					</select><br />
					<label>备注:</label>
					<textarea v-bind:value="mark"></textarea><br />
					确认<input type="checkbox" v-model="flag" />
					<input type="submit" v-bind:disabled="show" v-on:click.once="doSubmit" />
				</li>
			</ul>
		</div>
	</body>
	<script>
		new Vue({
			el: '#app',
			data() {
				return {
					uname: null,
					upwd: null,
					age: 10,
					sex: 1,
					hobby: [{
						id: 1,
						name: '篮球'
					}, {
						id: 2,
						name: '足球'
					}, {
						id: 3,
						name: '象棋'
					}],
					hobbies: [],
					types: [{
						id: 1,
						name: 'A'
					}, {
						id: 2,
						name: 'B'
					}, {
						id: 3,
						name: 'C'
					}],
					type: null,
					mark: '学生备注',
					flag: false
				}
			},
			computed: {
				show: function() {
					return !this.flag;
				}
			},
			methods: {
				doSubmit: function() {
					console.log('doSubmit')
					var obj = {
						uname: this.uname,
						upwd: this.upwd,
						age: this.age + 10,
						sex: this.sex,
						hobbies: this.hobbies,
						type: this.type,
						mark: this.mark,
					}
					console.log(obj);
				}
			}

		})
	</script>
</html>

 


总结

本文仅仅简单讲述了vue的事件处理器,自定义组件以及组件通信。如有错误还望指正。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值