Vue中的Prop属性 - 父传子
Prop的作用为父组件向子组件单向传递数据,这是一个单向数据流。父级prop的数据更新会向下流动到子组件中。
-
子组件 BlogTitle.vue
在子组件中声明props属性,用来接收父组件传递的数据。
<template> <div class="son"> <h1>这是子组件</h1> <h3>{{ title }}</h3> <h3>{{ age }}</h3> <h3>{{ sex }}</h3> </div> </template> <script> export default { name: "BlogTitle", //接受并对数据进行检测 props:{ title: String, age: { type: Number, default: 99 //默认值 }, sex: { type: String, required: true } }, setup(props){ console.log(props.title); } } </script>
-
父组件 BlogView.vue
先在script中引用BlogTitle.vue,然后在components属性加入子组件名称。
最后,可在setup中定义需要传输的数据。
<template> <div class="father"> <h1>这是父组件</h1> <BlogTitle :title="msg" sex="男" /> <h1>--------------</h1> <BlogTitle v-for="post in this.posts" :key="post.id" :title="post.title" /> </div> </template> <script> // 1. 引用BlogTitle.vue import BlogTitle from "@/components/BlogTitle"; import {reactive, ref} from 'vue' export default { name: "BlogView", //2. 加入BlogTitle components: { BlogTitle }, // setup() { const msg = ref("这是标题"); /** * 1. ref()和reactive()一样,都是实现响应式数据的方法。 * 2. reactice()必须传递一个对象,而ref可以实现简单值的监听。 * 3. ref本质为reactice, ref(xxx) -> reactice({value:xx}) * */ //3. 定义传输的数据 const posts = reactive([ {id: 1, title: 'My journey with Vue'}, {id: 2, title: 'Blogging with Vue'}, {id: 3, title: 'Why Vue is cool'} ]); return {posts, msg}; } } </script>
Vue3的特性函数 - setup
- setup函数处于beforeCreate和Created两个钩子函数之间的函数。setup无法使用data和methods中的数据和方法。
- 在setup函数中定义的变量和方法最后都是需要return出去的,不然无法在模板中使用
vue组件通信 - 子传父
子传父
- 需要触发一个事件,在这个事件中使用this.$emit(“父组件使用的事件名”,“子组件的数据”),
- 通过$emit事件名抛出,父组件调用抛出的事件名,并获取到子组件的传输来的数据。
子组件 ButtonCom.vue
<template>
<h3>{{ title }}</h3>
<button @click="onCount">{{ this.count }}</button>
<!-- 1. 组件事件 : 通过内置方法$emit()方法,将事件名称抛出一个事件-->
<!-- this.$emit("父组件使用的事件名","子组件的数据"),-->
<button @click="$emit('enlarge-text',this.postFontSize)">Enlarge Text</button>
</template>
<script>
export default {
//通过props, 父组件中定义的数据就可以传递到组件实例上。
//字符串组声明props
props: ['title'],
//对象的形式声明props
//2. 声明需要抛出
emits: ['enlarge-text'],
data() {
return {
count: 0,
//子组件需要传递的数据
postFontSize: 1
}
},
methods: {
onCount() {
this.count++;
}
},
name: "ButtonCom"
}
</script>
父组件HomeView.vue
<template>
<div>
<div :style="{fontSize: postFontSize + 'em'}">
<!-- 1. @后为子组件中的$emit('enlarge-text',1)定义的事件名 -->
<ButtonCom
v-for="post in this.posts"
:key="post.id"
:title="post.title"
@enlarge-text="AddFontSize"
>
</ButtonCom>
</div>
</div>
</template>
<script>
// 引用并使用组件
import ButtonCom from '@/components/ButtonCom.vue'
export default {
name: 'HomeView',
data() {
return {
posts: [
{id: 1, title: 'My journey with Vue'},
{id: 2, title: 'Blogging with Vue'},
{id: 3, title: 'Why Vue is so fun'}
],
postFontSize:1
}
},
//组件都被挂载后执行。通常模板渲染成html后调用,在对html的dom节点进行一些操作。
//确保渲染页面中 DOM的相关操作被客户端执行
mounted() {
},
methods: {
//2. 这里接受的n为 $emit('enlarge-text',4) 的4。
AddFontSize(n){
this.postFontSize += n;
}
},
components: {
ButtonCom
}
}
</script>