vue Sync

徐友樵
2023-12-01

vue sync选项

父组件

...
// <testsync :title="doc.title" @update:title="doc.title = $event" />
<testsync :title.sync="doc.title" />
...
data() {
    return {
      doc: {
        title: "fatherTitle",
        test: "test",
      },
    };
  },

子组件

<h1 @click="changeTitle">{{ title }}</h1>

export default {
  props: ["title"],
  data() {
    return {
      newTitle: "sonTitle",
    };
  },
  methods: {
    changeTitle() {
      this.$emit("update:title", this.newTitle);
    },
  },
};

用一个对象同时设置多个 prop 的时候:
父组件:

<testsync v-bind.sync="doc" /> 

data() {
    return {
      doc: {
        title: "fatherTitle",
        test: "fatherTest",
      },
    };
  },

子组件:

<template>
  <div>
    <h1 @click="changeTitle">{{ title }}</h1>
    <h1 @click="changeTest">{{ test }}</h1>
  </div>
</template>

<script>
export default {
  props: ["title", "test"],
  data() {
    return {
      newTitle: "sonTitle",
      newTest: "sonTest",
    };
  },
  methods: {
    changeTitle() {
      this.$emit("update:title", this.newTitle);
    },
    changeTest() {
      this.$emit("update:test", this.newTest);
    },
  },
};
</script>
 类似资料:

相关阅读

相关文章

相关问答