【Vue】局部组件(基础版)
2019-01-05 本文已影响0人
德育处主任
![](https://img.haomeiwen.com/i7275569/cd9b5566af02ab97.jpg)
相比起全局组件,局部组件只能在同一个实例内才能被调用。
本节目录
- 效果展示
- 代码讲解
局部组件的写法和全局组件差不多。
唯一不同就是:局部组件要写在Vue实例里面。
HTML代码:
<body>
<div id="app">
<rabbit></rabbit>
</div>
</body>
JS代码
new Vue({
// 选择根元素
el: '#app',
// 创建组件,
// components,注意末尾有 ‘s’,
// 而全局组件是不用家 ‘s’ 的。
// 这意味着,components 里可以创建多个组件。
components: {
// 定义组件名
'rabbit': {
// 组件结构
template: `<button>{{msg}}</button>`,
// data数据
data: function() {
return {
msg: 'Rabbit'
}
}
}
}
})
看 js 的注释。
打开HTML页面,可以看到一个 button了。
![](https://img.haomeiwen.com/i7275569/1dd4c2e4cae930b5.png)
第二个写法:把组件的布局写在 html 代码里。
HTML代码
<body>
<div id="app">
<rabbit></rabbit>
</div>
<!--自定义组件结构-->
<template id="rabbit_tpl">、
<div>
<button>{{ msg }}</button>
<p>上面是{{ msg }}按钮</p>
</div>
</template>
</body>
JS代码
new Vue({
el: '#app',
components: {
'rabbit': {
// 引用 html 里需要用到的组件 id
template: `#rabbit_tpl`,
data: function() {
return {
msg: 'Rabbit'}
}
}
}
})
![](https://img.haomeiwen.com/i7275569/a085af5758264c68.png)
上面这种写法,浏览器会把 html 里的 template 标签过滤掉。所以 template 标签的内容是不会在页面中展示的。直到它被 JS 中的 Vue 调用。
在 html 中,template 标签一定要有一个 id,因为通过 id 是最直接被选中的。
data 和 methods 等 参数,全部都要放到 Vue 实例里面写。
如果不想在 html 里用 template 标签,也可以用上一节所讲的,ES6的写法,可以换行书写 组件 的布局。