1. 父组件向子组件传递的数据,通过props进行传递,我们可以把props理解为属性。props传递存在两种格式,一种是数组格式,另一种是对象类型格式。其中第二种对象类型可以设置是否为必须数据,以及是否存在默认值数据。
//数组
//父组件
<HelloWorld :title="title"></HelloWorld>
//子组件
props: ["title"],
//对象
//父组件:
<HelloWorld :title="title"></HelloWorld>
//子组件:
props: {
title:{
type:String,
required:true,
default() {
return "我是title"
}
}
},
//上面default为什么是一个函数?
因为是一个组件,组件在其他组件都能使用,并且如果default是一个key;value形式,并且value是一个引用
类型的值,则如果要更改props的值,则其他组件的值也会更改。
2.子组件传递给父组件
1、当子组件有一些事情发生的时候,比如在组件中发生点击,父组件需要切换内容。
2、子组件有一些内容想要传递给父组件。
3、子组件通过$emit()触发事件,并且在emits中进行注册事件。
4、注册的事件可以是数组类型的,也可以是对象类型。
//子组件
<template>
<button @click="increment">+1</button>
<button @click="decrement">-1</button>
</template>
<script>
export default {
emits:["add", "sub"],
data() {
return {
}
},
methods: {
increment: function () {
this.$emit("add")
},
decrement: function () {
this.$emit("sub")
},
},
};
</script>
<style scoped></style>
//父组件
<template>
<h1>当前的数字是:{{counter}}</h1>
<HelloWorld @add="addOne" @sub="subOne"></HelloWorld>
</template>
<script>
import HelloWorld from "./components/HelloWorld.vue"
export default {
components: { HelloWorld },
data() {
return {
counter: 0
}
},
methods:{
addOne() {
this.counter++
},
subOne() {
this.counter--
}
}
}
</script>
<style scoped></style>