vuejs 子传父,父传子的应用实例
程序员文章站
2022-05-15 17:50:01
...
假设父文件为parent.vue
子文件,也是子组件,为child.vue
- 没有写子传父的方法的话,在子组件中是不能改变父组件传过来的值的,否则vue机制会报错。
- currentIndex是父组件要传给子组件的,当父组件的currentIndex发生变化,子组件的它也会发生变化,但是如果子组件的currentIndex变化,会被认为成是逆向的改变,报错。
- 但是现在我需要在子组件中的currentIndex变化能传回父组件,所有此时要用到子传父,$emit。
一、父传子
主要使用prop
parent.vue 传
1、引入子组件,在script中
import catalogue from "@/components/homePage/course/courseComm.vue";
2、组件注册
components: {
catalogue
},
3、在template标签中使用组件,父组件传值写在调用的组件里面,要传什么就:name=“value”,name是自己定义的名字,value是data中的数据
<catalogue :currentIndex="currentIndex" :type="2"></catalogue>
child.vue 接收
1、接收
export defalut{
props: ["currentIndex", "type",],
}
2、定义
export defalut{
data() {
return {
currentIndexs:this.currentIndex,
types:this.type,
};
},
}
二、子传父
主要使用$emit
child.vue 传
1、添加点击事件
<div @click="childpassBtn(0))"></div>
2、利用childpassBtn方法传值
methods:{
childpassBtn: function(index) {
//$emit的第一个为传的参的名字,第二个为传的值
this.$emit("passtoparent", index);
},
}
parent.vue 接收
1、调用子组件,在调用的子组件中写接收
//passtoparent为参数名,要与子组件中定义的一致,currentIndexChild是自己定义的名字
<catalogue v-on:passtoparent="currentIndexChild" ></catalogue>
2、使用
methods: {
// 接收子组件传过来的值
currentIndexChild: function(current) {
//currentIndex是在data()中定义好的
this.currentIndex = current;
},
}
上一篇: vuejs 数据绑定原理