概要
- 组件基础
-
一、组件基础
1、创建组件
2、组件的组成
template:相当于组件结构(html)
- 必须有且仅有一个根元素
- script:相当于业务逻辑(js)
style:相当于样式结构(css)
组件之间的调用是没有限制的
- 通常一个应用会以一颗嵌套的组件树的形式来组织
二、组件传递数据
1. 父传子:props
<template>
<div id="app">
<img alt="Vue logo" src="./assets/logo.png" />
<HelloWorld msg="Welcome to Your Vue.js App" />
<!-- 3.使用组件 -->
<Header :fatherInfo="fatherInfo"></Header>
</div>
</template>
<script>
import HelloWorld from "./components/HelloWorld.vue";
import Header from "./components/header.vue"; // 1.引入组件
export default {
name: "App",
components: {
HelloWorld,
Header, // 2.注册组件
},
data() {
return {
fatherInfo: "我是来自APP.vue的信息"
};
}
};
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
<template>
<div>
<button class="btn">
按钮 {{ fatherInfo }}
</button>
</div>
</template>
<script>
export default {
props: ["fatherInfo"]
};
</script>
<style scoped>
.btn {
width: 300px;
height: 300px;
background-color: coral;
}
</style>
2. 子穿父:自定义事件
<template>
<div>
<button class="btn" @mouseover="over" @mouseout="out">
按钮
</button>
</div>
</template>
<script>
export default {
data() {
return {
overInfo: "我进来了",
outInfo: "我出去了",
};
},
methods: {
over() {
// 父级在使用该组件的过程中,可以通过 @事件名称 来注册绑定事件函数
this.$emit("onOver", this.overInfo);
},
out() {
this.$emit("onOut", this.outInfo);
},
},
};
</script>
<style scoped>
.btn {
width: 300px;
height: 300px;
background-color: coral;
}
</style>
<template>
<div id="app">
<img alt="Vue logo" src="./assets/logo.png" />
<HelloWorld msg="Welcome to Your Vue.js App" />
<p>{{ info }}</p>
<!-- 3.使用组件 -->
<Header @onOver="getOverInfo" @onOut="getOutInfo" ></Header>
</div>
</template>
<script>
import HelloWorld from "./components/HelloWorld.vue";
import Header from "./components/header.vue"; // 1.引入组件
export default {
name: "App",
components: {
HelloWorld,
Header, // 2.注册组件
},
data() {
return {
info: "",
};
},
methods: {
getOverInfo(msg) {
this.info = msg;
},
getOutInfo(msg) {
this.info = msg;
},
},
};
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>