假设父组件为parent.vue,子组件为child.vue
- 没有写子传父的方法的话,在子组件中是不能改变父组件传过来的值的,否则vue机制会报错。
- currentIndex是父组件要传给子组件的,当父组件的currentIndex发生变化,子组件的它也会发生变化,但是如果子组件的currentIndex变化,会被认为成是逆向的改变,报错。
- 但是现在我需要在子组件中的currentIndex变化能传回父组件,所有此时要用到子传父,$emit。
一、父传子
主要使用prop
parent.vue 传
1、引入子组件,在script中
import catalogue from "@/components/child.vue";
2、局部组件注册
components: {
catalogue
},
3、在template标签中使用组件,父组件传值写在调用的组件里面,要传什么就v-bind:name=“value”,name是自己定义的名字,value是data中的数据。v-bind可以缩写成:
<catalogue :currentIndex="currentIndex" :type="2"></catalogue>
child.vue 接收
1、接收
export defalut{
props: ["currentIndex", "type",],
}
2、使用
直接this.currentIndex,this.type
二、子传父
child.vue 子组件传值
1、添加点击事件,点击时进行传值
<div @click="passVal()"></div>
2、利用$emit向父组件传值
methods:{
passVal: function() {
//$emit的第一个为传的参的名字,第二个为需要传的值
this.$emit("sendVal", this.currentIndex);
},
}
parent.vue 父组件接收
1、调用子组件,在调用的子组件中写接收
//sendVal为参数名,要与子组件中定义的一致,getVal是自己定义的方法名。v-on可缩写为@
<catalogue v-on:sendVal="getVal" ></catalogue>
2、使用
methods: {
// 接收子组件传过来的值
getVal: function(value) {
//value是$emit函数里传的值
// 可对value进行一些操作
},
}