Vue组件的使用

组件是可复用的 Vue 实例, 如果网页中的某一个部分需要在多个场景中使用,那么我们可以将其抽出为一个组件进行复用。组件大大提高了代码的复用率。

一、全局注册

Vue.component('componentNew', { /* ... */ })

第一个参数为组件名,第二个参数为配置项,是一个对象的结构。
全局注册的组件可以用在任何新创建的 Vue 根实例 (new Vue)的模板中。

二、局部注册

var vm = new Vue({
	el : '#app',
	components:{
                'componentNew':{ /* ... */ }
                },
})

对于 components 对象中的每个 property 来说,其 property 名就是自定义元素的名字,其 property 值就是这个组件的选项对象。
局部注册的组件在其子组件中不可用。

三、复合组件

Vue.component('component-fatner', {
	template : `<div>
		<component-son></component-son>				//引入子组件
	</div>`
})
Vue.component('component-son', {
	template : `<div>
		<h1>this is component-son</h1>
	</div>`
})

四、组件绑定数据与传值

Vue.component('component-fatner', {
	template : `<div>
		<h1>姓名:{{ name }} 年龄:{{ age }}</h1>
	</div>`,
	data(){
		return{
			age : 20
		}
	},
	//props:['name'] 数组形式
	props:{
	    name:{
	        type : String,//设置传值的类型
	        default : 'jack',//设置传值的默认值
	        required : true,//设置是否为必须传值
	    }
	}
})

绑定数据必须为**return{…}**的形式。
props用于传递数据,对象形式的写法可以给传参设置限制。

五、查看组件的属性
首先通过ref给子组件做一个标记
在父组件中,通过$refs就可以访问子组件
在子组件中,通过$parent就可以访问父组件

Vue.component('component-fatner', {
	template : `<div>
		<h1>this is component-fatner</h1>
		<button @click="getson"></button>
		<component-son ref="son"></component-son>
	</div>`,
	methods : {
		getson(){
			console.log(this.$refs);
		}
	}
})
Vue.component('component-son', {
	template : `<div>
		<h1>this is component-son</h1>
		<button @click="getparent"></button>
	</div>`,
	methods : {
		getparent(){
			console.log(this.$parent);
		}
	}
})
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值