vue.js中组件的创建和使用方法
vue.js中创建组件有三个步骤:创建组件构造器,注册组件以及使用组件。下边以实际例子说明组件的定义及使用方法。同时提供了使用语法糖的简单写法的例子
·
vue.js中创建组件有三个步骤:创建组件构造器,注册组件以及使用组件。
一、创建组件构造器
创建组件构造器的方法很简单,只需要以下语句即可:
var MyCompontent=Vue.extend({...});
然而这个时候还不能直接使用组件,需要把组件注册到应用中。
var MyCompontent=Vue.extend({...});
然而这个时候还不能直接使用组件,需要把组件注册到应用中。
二、注册组件
Vue.js提供了两种注册组件的方式,分别为全局注册和局部注册,下边分别介绍:
全局注册:需要确保在根实例初始化之前注册,这样才能使组件在任意实例中都可以使用。注册方式如下:
Vue.component('my-component',MyComponent);//此句一定要放在new Vue({...});之前
注册过程中也指定了组件的HTML标签。本例为<my-component>;
局部注册:限定了组件只能在被注册的组件中使用,而无法在其他组件中使用。
全局注册:需要确保在根实例初始化之前注册,这样才能使组件在任意实例中都可以使用。注册方式如下:
Vue.component('my-component',MyComponent);//此句一定要放在new Vue({...});之前
注册过程中也指定了组件的HTML标签。本例为<my-component>;
局部注册:限定了组件只能在被注册的组件中使用,而无法在其他组件中使用。
三、使用组件
基于以上对组件的介绍,下边以一个具体的例子说明组件的使用方法。
全局注册使用方法:
局部注册使用方法:
以上代码最终在浏览器的中的渲染结果相同。只是全局注册的my-component标签可以在HTML文档中任何地方使用,而局部注册的my-compoment标签只能在id为app的容器下使用。
<div id="app">
<my-component></my-component>
</div>
<script src="vue.js"></script>
<script>
/*创建组件构造器*/
var MyComponent = Vue.extend({
template: '<p>This is a component</p>'
});
/*全局注册组件*/
Vue.component('my-component', MyComponent);
/*使用组件*/
var vm = new Vue({
el: '#app'
})
</script>
<div id="app">
<my-component></my-component>
</div>
<script src="vue.js"></script>
<script>
var child = Vue.extend({
template: '<p>This is a component</p>'
});
var vm = new Vue({
el: '#app',
components: {
'my-component': child
}
});
</script>
四、语法糖表示法
vue.js对于以上两种注册方法提供了简化方法,我们可以在注册组件的时候定义组件构造器。举例如下:
<div id="app">
<my-component></my-component>
</div>
<script src="vue.js"></script>
<script>
/**全局注册
Vue.component('my-component', {
template: '<p>This is a component</p>'
});
new Vue({
el: '#app'
});*/
//局部注册
new Vue({
el: '#app',
components: {
'my-component': {
template: '<p>This is a component</p>}'
}
}
})
</script>
更多推荐
已为社区贡献4条内容
所有评论(0)