组件注册
局部注册组件
//组件调用
<div>
<Left></Left>
</div>
//组件导入
import Left from '@/components/Left.vue'
//组件注册
export default{
components:{
Left
}
}
全局注册
在 vue 项目的 main.js 入口文件中,通过 Vue.component() 方法,可以注册全局组件。示例代码如下:
import Left from '@/components/Left.vue'
//全局注册
//参数1:字符串格式,表示"组件名称"
//参数2:需要被全局注册的那个组件
Vue.component('MyLeft',Left)
// 组件调用
<my-left></my-left>
组件传参
父组件向子组件共享数据
props接收参数的几种方式:
export default {
// 第一种格式
props: ['prams1'],
// 第二种格式
// props:{
// prams1: Number,
// },
// 第三种格式
// props:{
// prams1: {
// type: Number,
// default: 100
// },
// },
父组件源码
<template>
<div>
<son :msg="message" :user="userinfo"></son>
</div>
</template>
<script>
import Son from './Son'
export default {
components: {
Son
},
data() {
return {
userinfo: "用户信息1212",
message: "我的消息1212"
};
},
};
</script>
子组件源码
<template>
<div>
<h1>我是子组件</h1>
<p>{{user}}</p>
<p>{{msg}} </p>
</div>
</template>
<script>
export default {
props:["user","msg"],
data() {
return {};
},
};
</script>
子组件向父组件共享数据
子组件向父组件共享数据使用自定义事件。示例代码如下
父组件Parent.vue源码:
<template>
<div class="pp">
<h1>父组件</h1>
<h1 class="xs">{{ num }}</h1>
<son @numchange="getNewCounter"></son>
</div>
</template>
<script>
import Son from "./Son";
export default {
components: {
Son,
},
data() {
return {
num: 1,
};
},
methods: {
getNewCounter(val) {
console.log("父组件得到的参数", val);
this.num = val;
},
},
};
</script>
<style scoped>
.pp {
background-color: rgb(255, 0, 0);
border-color: black;
padding: 30px;
}
.xs {
height: 20px;
width: 20px;
}
</style>
子组件Son.vue源码:
<template>
<div class="ss">
<button @click="add">子组件加1</button>
</div>
</template>
<script>
export default {
data() {
return {
count: 1,
};
},
methods: {
add() {
this.count += 1;
this.$emit("numchange", this.count);
console.log("子组件", this.count);
},
},
};
</script>
<style scoped>
.ss {
background-color: rgb(64, 140, 68);
margin: 10px;
}
</style>
兄弟组件之间的数据共享
在 vue2.x 中,兄弟组件之间数据共享的方案是EventBus
EventBus 的使用步骤
① 创建 eventBus.js 模块,并向外共享一个 Vue 的实例对象
② 在数据发送方,调用 bus.$emit('事件名称', 要发送的数据) 方法触发自定义事件
③ 在数据接收方,调用 bus.$on('事件名称', 事件处理函数) 方法注册一个自定义事件