Vue之组件详解

Vue.js(读音 /vjuː/, 类似于 view) 是一套构建用户界面的渐进式框架。
Vue 只关注视图层, 采用自底向上增量开发的设计。
Vue 的目标是通过尽可能简单的 API 实现响应的数据绑定和组合的视图组件。
组件使Vue功能更加强大
好处是: 1, 拓展HTML元素;2,封装
语法
Vue.component(tagName, options)
tagName 组件名, options 选项
用法: <tagName></tagName>
全局组件
<div id = "div1">
	<tagName1></tagName1>
</div>
<script>
	Vue.component
	('tagname1',{ template:'<h1>我是Vue组件</h1>'}
	)
	new Vue({
	el: "#div1"
	})
</script>
细节点:
Html 不区分大小写
Vue 声明组件的时候务必使用小写
局部组件
<div id="app1">
	<tagname></tagname>
</div>

<script>
	var test = {
	template : '<h2>hdkjahfjafha</h2>'
	}
	new Vue(
		{
		el: "#app1",
		components : {
		'tagname' : test
		}
	}
	)
</script>
细节点:
templte 内容中的数据:  携标签名
Prop
<div id="app">
	<child message="hello!"></child>
</div>

<script>
	Vue.component(
		'child',{
		props : ['message'],
		template : '<span>{{message}}</span>'
	})
// 创建根实例
new Vue({
	 el: '#app'
})
</script>
动态Prop
<div id="app">
	<div>
 	 <input v-model="parentMsg">
	  <br>
  	<child v-bind:message="parentMsg"></child>
	</div>
</div>

<script>
// 注册
Vue.component('child', {
// 声明 props
 props: ['message'],
// 同样也可以在 vm 实例中像 “this.message” 这样使用
 template: '<span>{{ message }}</span>'
})
// 创建根实例
new Vue({
	el: '#app',
	data: {
		parentMsg: '父组件内容'
	  }
})
</script>
Prop验证
Vue.component('example', {
	props: {
	 // 基础类型检测 (`null` 意思是任何类型都可以)
		propA: Number,
		// 多种类型
	 propB: [String, Number],
	 // 必传且是字符串
	 propC: {
 		 type: String,
		  required: true
	},
	// 数字,有默认值
 propD: {
 		 type: Number,
  		default: 100
  },
 // 数组/对象的默认值应当由一个工厂函数返回
	propE: {
 		 type: Object,
  		default: function () {
    	return { message: 'hello' }
 		 }
 },
	// 自定义验证函数
	 propF: {
			  validator: function (value) {
   			 return value > 10
 				 }
	 }
	 }
	})
自定义事件
<div id="app">
<div id="counter-event-example">
  <p>{{ total }}</p>
  <button-counter v-on:increment="incrementTotal"></button-counter>
  <button-counter v-on:increment="incrementTotal"></button-counter>
</div>
</div>

<script>
	Vue.component('button-counter', {
	 template: '<button v-on:click="incrementHandler">{{ counter }}</button>',
	 data: function () {
	 return {
 		 counter: 0
		}
	 },
	methods: {
	 incrementHandler: function () {
 		 this.counter += 1
 		 this.$emit('increment')
	  }
	},
	})
	new Vue({
	  el: '#counter-event-example',
	data: {
	 total: 0
	},
	 methods: {
		incrementTotal: function () {
  		this.total += 1
		}
	}
	})
	</script>
更多文章,请关注博客
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值