1. 程式人生 > >Vue —— 父子通訊高階用法

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>

連結

  • https://www.cnblogs.com/gsgs/p/7294160.html