1、vue使用sync方法,子组件修改父组件的值
一、在父组件中使用修饰符sync修饰变量popup
.sync修饰符可以实现子组件与父组件的双向绑定,并且可以实现子组件同步修改父组件的值。
<child :show.sync="show" ></myPopup>
二、在子组件中
<button @click="change1">点击我,改变show值</button>
change1(){
this.$emit('update:show','加油');
}
简单的说就是:
//父组件将age传给子组件并使用.sync修饰符。
<parent :name.sync="name">
</parent >
//子组件触发事件
mounted () {
console.log(this.$emit('update:name',"张三"));
}
2、vue使用自定义事件方法,子组件修改父组件的值
子组件
{{title}}
<button @click="change1"></button>
props:["title]
methods:{
change1(){ this.$emit('change','标题'); }
}
父组件
<child2 :title="title" @change="getChange"></child2>
getChange(value) {
this.title = value;
}
3、项目中的使用
父组件中 多次使用同一组件,传递不同的数组
<pictureUpload label="杆塔基础整体图片(包含杆号牌)" :list.sync="addForm.fileBaseList"></pictureUpload>
<pictureUpload label="现场开挖图片" :list.sync="addForm.fileNowList"
></pictureUpload>
在子组件中声明一个fileList,将fileList赋值给到传递过来的list
watch: {
fileList(val) {
this.$emit("update:list", val);
},
},
4、强化演示
子组件也通过事件改变了父组件中的title。可使用在关闭弹窗等场景。
子组件
<p>子组件:{{title}}</p>
<button @click="change1">点击我,改变title值</button>
export default {
props:{
title:{
type:String
}
},
methods:{
change1(){
this.$emit('update:title','加油');
}
}
};
</script>
父组件
<p>父组件:{{title}}</p>
<child2 :title.sync="title"></child2>
<script>
import child2 from "./child2.vue";
export default {
components: {child2},
data() {
return {
title: "努力着,从不放弃"
};
}
};
</script>
5、父组件调用子组件的事件
//父组件里声明ref
<template>
<div class="parent">
<Child ref="child"></Child>
</div>
</template>
methods: {
parentMethod(){
this.$refs.child.childMethod();
}
}
//子组件里
methods: {
childMethod() {
alert("我是子组件的方法!")
}
}