一、组件的使用
1、全局-注册使用
在入口文件main.js,new Vue之上注册
import Pannel from 'vue组件路径'
Vue.component('组件名', 组件对象)
组件名当标签使用:
<组件名></组件名>
2、局部-注册使用
<script>
// 局部引入组件
import Pannel from 'vue组件路径'
export default {
// 局部注册组件
components: {
组件名: 组件对象
}
}
</script>
组件名当标签使用
二、组件通信
1、父向子-props
子组件
<template>
<div id="son_01">{{ people }}喜欢 {{ fruit }}</div>
</template>
<script>
export default {
// 接收变量
props: ['people', 'fruit']
}
</script>
<style>
</style>
父组件
<template>
<div>
<!-- 传值 -->
<S1 people="张三" fruit="苹果"></S1>
</div>
</template>
<script>
// 引入组件,注册使用组件
import S1 from './components/son_01'
export default {
components:{
S1
}
}
</script>
<style>
</style>
2、父向子-配合循环
父组件
<!-- 循环传值 -->
<S1 v-for="(obj,index) in list" :key="index" :people="obj.people" :fruit="obj.fruit"></S1>
data() {
return {
list: [
{
people: "李四",
fruit: "香蕉"
},
{
people: "王五",
fruit: "西瓜"
},
{
people: "赵六",
fruit: "哈密瓜"
},
]
}
}
单向数据流:
-
父组件的数据发生了改变,子组件会自动跟着变
-
子组件不能直接修改父组件传递过来的props props是只读的
==父组件传给子组件的是一个对象,子组件修改对象的属性,是不会报错的,对象是引用类型, 互相更新==
3、子向父
从子组件把值传出来给外面使用
语法:
-
父: @自定义事件名="父methods函数"
-
子: this.$emit("自定义事件名", 传值) - 执行父methods里函数代码
子组件
<template>
<div>
<button @click="sendFn">发送</button>
</div>
</template>
<script>
export default {
methods: {
sendFn(){
this.$emit('send','hello')
},
}
}
</script>
父组件
<template>
<div>
<S2 @send="fn"></S2>
</div>
</template>
<script>
import S2 from './components/son_02'
export default {
components: {
S2
},
methods: {
fn(n) {
console.log(n);
}
}
}
</script>
4、跨组件通信
1、定义事件总线bus对象
import Vue from 'vue'
// 导出空白vue对象
export default new Vue()
发送方
<template>
<div>
<h3>发送者:{{ name }}</h3>
<button @click="send">点击发送数据</button>
</div>
</template>
<script>
import eventBus from '../EventBus'
export default {
data() {
return {
name: 'A'
}
},
methods: {
send() {
eventBus.$emit('mysend', '发送者'+this.name)
}
}
}
</script>
<style>
</style>
接收方
<template>
<div>
<h3>{{ name }}发来了一条信息</h3>
</div>
</template>
<script>
// 目标: 跨组件传值
// 1. 引入空白vue对象(EventBus)
// 2. 接收方 - $on监听事件
import eventBus from '../EventBus'
export default {
data(){
return {
name:""
}
},
created(){
eventBus.$on('mysend',v=>{
console.log('来信息了',v);
})
}
}
</script>
<style>
</style>
父组件
<template>
<div id="app">
<Send></Send>
<Accept></Accept>
</div>
</template>
<script>
import Send from './components/Send'
import Accept from './components/Accept'
export default {
components: {
Send,
Accept,
}
}
</script>
<style>
</style>