Vue —— 父子通信高级用法
async
-
父组件使用
:syncVal.sync="val"
<template> <section class="parent"> <son :syncVal.sync="val"></son> </section> </template> <script> import Son from "@/components/test/Son"; export default { data() { return { val: 1 }; }, components: { Son } }; </script>
-
子组件使用
this.$emit("update:syncVal", this.$attrs.syncVal + 1);
<template> <section class="son"> <span>{{$attrs.syncVal}}</span> <button @click="clickFn">点击</button> </section> </template> <script> export default { methods: { clickFn() { this.$emit("update:syncVal", this.$attrs.syncVal + 1); } } }; </script>
model
-
父组件使用
v-model
<template> <section class="parent"> <son v-model="val"></son> </section> </template> <script> import Son from "@/components/test/Son"; export default { data() { return { val: 10 }; }, components: { Son } }; </script>
-
子组件使用
this.$emit("changParent", this.val1 + 1);
<template> <section class="son"> <span>{{val}}</span> <button @click="clickFn">点击</button> </section> </template> <script> export default { // 子组件自定义 prop 和 event model: { prop: "val", event: "changParent" }, props: ["val1"], created() { console.dir(this); }, methods: { clickFn() { this.$emit("changParent", this.val1 + 1); } } }; </script>
-
子组件使用的另外一种方法,
value 是必须的
,this.$emit("input", this.value + 1);
<template> <section class="son"> <span>{{value}}</span> <button @click="clickFn">点击</button> </section> </template> <script> export default { props: { value: { default: "" } }, created() { console.dir(this); }, methods: { clickFn() { this.$emit("input", this.value + 1); } } }; </script>