注册一个组件
有两种方式可以注册一个组件,第一种是全局注册,第二种是局部注册
# 全局注册Vue.component('my-component',{ template: '<span>Hello</span>'})# 局部注册var child = { template: '<span>Hello</span>'}new Vue({ // ··· components:{ my-component: child }})
注意:组件的注册必须要在Vue实例创建之前
使用组件
<div id="app"> <my-component></my-component></div>
当我们需要使用到data时,data必须是一个函数,否则将会报错,这是Vue的一个规则,如下
Vue.component('my-component',{ template: '<span>{{message}}</span>', data:function(){ return {message:'hello'} }})
组件间消息传递
当我们封装了组件A,但是组件A又嵌套了组件B,这时候组件AB形成了父子组件的关系,我们应该怎么来让父组件传递消息给子组件呢,这里用到了一个属性值props,如下
Vue.component('my-component',{ props: ['message'] template: '<span>{{message}}</span>'})# 通过props传递消息给子组件<my-component message="Hello"></my-component>
上面的例子,我们通过props传递了参数给子组件,确实能改变子组件的值,但是,假如我们有这样一个要求,props的值是动态改变的,那么这种静态字面量传递参数的方式就不能满足我们的需求了。如下将说明如何进行动态的props值设定
<div id="app"> <input v-model="parentMsg"><br> <my-component v-bind:message="parentMsg"></div>
这里通过v-bind的命令,将我们的message与parentMsg进行绑定,这样,当我们的parentMsg改变时,message将能实时改变
自定义事件
父子组件之间如果通过props来传递数据的话,那么似乎只能进行单向的数据传递,只能从父组件向子组件传递,假如我们需要从子组件传递消息回去,那么就需要用到自定义事件了
# 使用v-on绑定自定义事件Vue.component('my-component',{ template: '<button v-on:click="increment">{{counter}}</button>', data: function(){ return {counter: 0} }, methods: { increment: function(){ this.counter += 1; this.$emit(increment); } }})new Vue({ el: '#app', data: { // ··· total:0 }, methods: { // ··· incrementTotal: function(){ this.total += 1; } }})
<div id="app"> // ··· <p>{{total}}</p> <my-component v-on:increment="incrementTotal"></my-component></div>
这里,我们点击按钮,按钮的显示的数值将会改变,同时,total的值也会动态的改变,这就是子组件回传数据的实例,我们点击按钮时,将会首先执行button的onclick方法,在onclick方法里面,通过this.$emit('increment')来执行我们自定义的事件,假如我们需要在$emit中添加参数,那么我们就要在$on()中进行回调的处理
新闻热点
疑难解答
图片精选