vue组件
组件 (Component) 是 Vue.js 最强大的功能之一,
创建组件
<body>
<div id="app">
<button-counter></button-counter>
</div>
<script type="text/javascript">
//全局定义组件(作用域隔离)
//可包含dom js逻辑 样式
Vue.component("navbar",{
Vue.component('button-counter', {
data: function () {
return {
count: 0
}
},
template: '<button v-on:click="count++">You clicked me {{ count }} times.</button>'
})
new Vue({
el:"#app"
})
</script>
</body>
组件复用
<div id="components-demo">
<button-counter></button-counter>
<button-counter></button-counter>
<button-counter></button-counter>
</div>
注意当点击按钮时,每个组件都会各自独立维护它的 count。因为你每用一次组件,就会有一个它的新实例被创建。
组件的组织
全局注册和局部注册。至此,我们的组件都只是通过 Vue.component 全局注册的:
Vue.component('my-component-name', {
// ... options ...
})
通过 Prop 向子组件传递数据
Prop 是你可以在组件上注册的一些自定义 attribute。当一个值传递给一个 prop attribute 的时候,它就变成了那个组件实例的一个 property。为了给博文组件传递一个标题,我们可以用一个 props 选项将其包含在该组件可接受的 prop 列表中:
Vue.component('blog-post', {
props: ['title'],
template: '<h3>{{ title }}</h3>'
})
监听子组件事件
我们可以通过添加一个 postFontSize 数据 property 来支持这个功能:
<div id="blog-posts-events-demo">
<div :style="{ fontSize: postFontSize + 'em' }">
<blog-post
v-for="post in posts"
v-bind:key="post.id"
v-bind:post="post"
></blog-post>
</div>
</div>
Vue.component('blog-post', {
props: ['post'],
template: `
<div class="blog-post">
<h3>{{ post.title }}</h3>
<button>
Enlarge text
</button>
<div v-html="post.content"></div>
</div>
`
})
解析 DOM 模板时的注意事项
有些 HTML 元素,诸如
-
、
- 、 和 ,对于哪些元素可以出现在其内部是有严格限制的。而有些元素,诸如
- 、
- 和 ,只能出现在其它某些特定的元素内部。