学习目标:
本文主要记录一下vue的父子组件数据传递的方法
学习内容:
- 声明组件
- 父组件向子组件传递数据
- 子组件向父组件传递数据
1.声明组件
-
全局注册
//创建app时候注册,使用component方法 app.component('todo-item', { template: `<li>This is a todo</li>` })
-
局部注册
//使用options的components属性注册,通过创建一个普通的 JavaScript 对象,然后挂载在app中 const ComponentA = { /* ... */ } const app = Vue.createApp({ components: { 'component-a': ComponentA, } })
-
当组使用app.component()注册时,component有两个参数,第一个参数是组件名,第二个是组件的定义(模板)。当只传入第一个参数的时候获取这个组件的定义,传入两个参数的时候表示注册这个组件
父向子传递
//parent.vue
<template>
<div>
<h2>这是父组件页面</h2>
<my-children msg="title" :arctile="obj"></my-children>
//在父组件中,子组件使用attribute可以传递文本字符串,但是如果使用:attribute的方式可以使用任何对象
</div>
</template>
<script >
//引入子组件
import myChildren from "./children.vue";
export default {
data() {
return {
obj: ["牛奶", "咖啡", "香蕉"],
};
},
//挂载组件,
components: {
myChildren,
},
};
</script>
<style >
</style>
//Children.vue
<template>
<div>
<h2>子组件的页面信息{{ msg }}</h2>
<ol>
<li v-for="item in arctile" :key="item">{{ item }}</li>
</ol>
</div>
</template>
<script >
export default {
data() {
return {
student: [],
};
},
props: ["msg", "arctile"],//使用props属性接收父组件传递过来的元素信息
components: {},
};
</script>
<style >
</style>
子向父传递数据,需要通过触发事件的形式来传递数据
//Children.vue
<template>
<div>
<h2>子组件的页面信息{{ msg }}</h2>
<button @click="changenum(2)">按钮</button>//1.定义触发事件和要传递的数据
</div>
</template>
<script >
export default {
data() {
return {
student: [],
};
},
props: ["msg", "arctile"],//使用props属性接收父组件传递过来的元素信息
components: {},
methods:{
changenum(num){
this.$emit("changenumEvent",num)//2.传递事件要通过$emit方法传递,第一个参数为在父组件中的事件名(自定义),第二个参数为要传递的参数
}
}
};
</script>
<style >
</style>
//parent.vue
<template>
<div>
<h2>这是父组件页面</h2>
<my-children @changenumEvent="demo"></my-children>//3.用子组件定义的事件名来写一个方法接收参数(方法名也为自定义的)
<h1>{{count}}</h1>
//
</div>
</template>
<script >
//引入子组件
import myChildren from "./children.vue";
export default {
data() {
return {
obj: ["牛奶", "咖啡", "香蕉"],
count:0
};
},
//挂载组件,
components: {
myChildren,
},
methods:{
demo(data){//4、使用自定义的方法名来接收数据,操纵数据
this.count += data;
}
}
};
</script>
<style >
</style>
其他传递方式
父子组件的访问方式
- 父组件访问子组件,首先在调用的子组件中添加一个ref(vue3的用法)属性,自定义ref名,然后可以使用this.$refs.自定义名.子组件的方法名或属性
- 子组件访问父组件,使用 t h i s . p a r e n t . 父组件的方法名或属性 , 支持链式调用,使用 this.parent.父组件的方法名或属性,支持链式调用,使用 this.parent.父组件的方法名或属性,支持链式调用,使用root可以访问根组件