参考:https://www.cnblogs.com/shaozhu520/p/10926647.html
父传子:props
父组件:
<template>
<div>
<p @click="Btn">点击我</p>
<Address :visible="showas" />
</div>
</template>
<script>
import Address from "@/components/newCard/address";
export default {
components: { Address },
data() {
return {
showas: false
};
},
methods: {
Btn() {
this.showas = true;
}
}
};
</script>
<style lang="scss">
</style>
子组件:
<template>
<div>
<p v-show="visible">能看见我吗?</p>
</div>
</template>
<script>
export default {
props:{
visible:Boolean
}
};
</script>
<style lang="scss">
</style>
子传父 :$emit
子组件:
<template>
<div>
<p @click="onZI">{{msg}}</p>
</div>
</template>
<script>
export default {
data() {
return {
msg: "点击改变"
};
},
methods: {
onZI() {
this.$emit("onValue","success");
}
}
};
</script>
<style lang="scss">
</style>
父组件:
<template>
<div>
<De @onValue="onFu" />
<p>{{message}}</p>
</div>
</template>
<script>
import De from "@/components/newCard/de";
export default {
components: { De },
data() {
return {
message: "cannot"
};
},
methods: {
onFu(e) {
this.message = e;
console.log(e);
}
}
};
</script>
<style lang="scss">
</style>
常见的双向绑定: .sync
父组件点击按钮显示子组件,点击子组件里面的关闭按钮,隐藏子组件 (常用于弹框组件)
父组件:
<template>
<div>
<p @click="Btn">点击显示子组件</p>
<De :VisibleIng.sync="shows" />
</div>
</template>
<script>
import De from "@/components/newCard/de";
export default {
components: { De },
data() {
return {
shows: false
};
},
methods: {
Btn() {
this.shows = true;
}
}
};
</script>
<style lang="scss">
</style>
子组件:
<template>
<div>
<div v-show="VisibleIng">
<p>我是内容</p>
<p class="btn" @click="onCancel">关闭内容</p>
</div>
</div>
</template>
<script>
export default {
props: {
VisibleIng: Boolean
},
methods: {
onCancel() {
this.$emit("update:VisibleIng", false);
}
}
};
</script>
<style lang="scss">
.btn {
color: red;
font-size: 0.5rem;
}
</style>
父组件点击按钮显示子组件,子组件里包含取消按钮和确定按钮,怎么判断点击子组件的显示还是隐藏,传同一个事件,传不同的参数,父组件里面判断根据点击的不同按钮,做相应的操作 (常用于弹框组件)
父组件:
<template>
<div>
<p @click="Btn">点击显示子组件</p>
<De :visible="shows" @onValue="onChangeValue" />
</div>
</template>
<script>
import De from "@/components/newCard/de";
export default {
components: { De },
data() {
return {
shows: false
};
},
methods: {
Btn() {
this.shows = true;
},
onChangeValue(e) {
console.log(e.type);
if (e.type === "确定") {
alert("我点击了确定");
this.shows = false;
} else {
alert("我点击了取消");
}
}
}
};
</script>
<style lang="scss">
</style>
子组件:
<template>
<div>
<div v-show="visible">
<p>我是内容</p>
<p class="btn" @click="onCancel">取消</p>
<p class="btn" @click="onFinsh">确定</p>
</div>
</div>
</template>
<script>
export default {
props: {
visible: Boolean
},
methods: {
onCancel() {
let obj = {
type: "取消"
};
this.$emit("onValue", obj);
},
onFinsh() {
let obj = {
type: "确定"
};
this.$emit("onValue", obj);
}
}
};
</script>
<style lang="scss">
.btn {
color: red;
font-size: 0.5rem;
}
</style>