Vue进阶之组件
创建并注册组件
- 全局创建注册
`Vue.component(tagName, options);`
- 局部创建注册
```
new Vue({
components: {
// <my-component> 将只在父模板可用
'my-component':'<h1>hellow world</h1>'
}
})
```
动态组件
通过使用保留的 <component> 元素,动态地绑定到它的 is 特性,我们让多个组件可以使用同一个挂载点,并动态切换
```
var vm = new Vue({
el: '#example',
data: {
currentView: 'home'
},
components: {
home: { /* ... */ },
posts: { /* ... */ },
archive: { /* ... */ }
}
})
```
```
<component v-bind:is="currentView">
</component>
//通过控制currentView来控制展示哪个组件
```
组件通信 (父子组件与非父子组件)
- 父子通信
父子组件的通信,主要是靠Prop
```
Vue.component('child', {
// 在子组件用父组件传进来的参数,需要声明 props
props: ['message'],
template: '<span>{{ message }}</span>'
})
<child message="by father"></child>
```
若是需要父组件改变状态,子组件跟着变动,就需要v-bind,
```
<child :message="by father"></child>
```
若是子组件想传递数据给父组件,可以:
```
Vue.component('child', {
data:function(){
return {
name:'child'
}
},
template: '<span @click="child">{{ name }}</span>',
methods:{
child:function(){
this.$emit('child',{name:'child'})
}
}
})
new Vue({
el: '#app',
data: {
name:'father'
},
methods: {
fatherSay: function (data) {
alert(data.name);//'child'
}
}
})
<child @child="fatherSay"></child>
```
- 非父子组件
```
var message = new Vue();
//在组件内
bus.$emit('hellow', 'eric')
// 在组件 B 创建的钩子中监听事件
bus.$on('hellow', function (id) {
// ...
})
//注意,$on 事件写在mounted里面。
```
单文件组件(.vue)
运用webPack 可以写.vue文件,里面有html,js,css.一个单文件组件。
```
<template>
<h1>hellow component</h1>
</template>
<script>
export default{
name:'app',
data () {
return {
}
}
}
</script>
<style scoped>
</style>
```
异步组件
在比较大型的应用中,打包成一个整个文件,会导致build.js文件过于太大。
我们可以用vue的异步组件,加webpack的code solit 功能,把build.js分成0.build.js,1.build.js.... 在页面运用当前组件的时候,才进行加载。避免了第一次登陆,加载时间过长的问题。
在写路由文件的时候:
```
const index = require('./views/index.vue')//普通组件
const index = resolve => require(['./views/index.vue'], resolve)//异步加载组件
```