vue中父子组件传值,怎么在子组件修改父组件的值呢?
答: 1.子组件想要修改时,须要经过**$emit派发一个自定义事件**,父组件收到后,由父组件进行修改
2.当你传入的prop为Object类型或者Array的时候,修改子组件内部的prop可以对应的改变父组件中的值(对象和数组是引用类型,指向同一个内存空间)
1,使用$emit派发的事件
**(1)、*子组件向父组件传递数据
$emit的理解:当我们点击按钮,子组件便会分发一个名为output的事件,父组件中使用函数接收该事件传递的数据。**
**父组件**
<template>
<div>
<p>{
{
initVal}}</p>
<Son ref="son" :fatherData='outputVal' @ouput='getSonVal'/>
</div>
</template>
<script>
import Son from "./son";
export default {
name: "father",
data() {
return {
initVal:'这是父组件自身的值'
};
},
components:{
Son
},
methods: {
getSonVal(val){
this.initVal=val
}
}
};
</script>
<style>
</style>
**子组件**
<template>
<div>
<el-button @click="ouputToFather">子组件中的按钮</el-button>
</div>
</template>
<script>
export default {
name: "Son",
data() {
return {
outSonVal:'我是子组件传递给父组件的数据'
};
},
methods: {
ouputToFather(){
this.$emit('ouput',this.outSonVal)//分发名为output的事件,将outSonVal的值发送出去
}
}
};
</script>
<style>
</style>
参考文档
1.https://www.jb51.net/article/142021.htm
2.http://www.javashuo.com/article/p-macfeagd-ca.html
3.https://blog.csdn.net/u010640592/article/details/123007042