Vue 中的双向数据绑定:无法从 child 组件更新 Parent 组件

Two way data binding in Vue: Unable to update the Parent component from the child component

我得到了以下两个组件:

Parent:

<template>
  <v-container>
    <v-row class="text-center">
      <v-col cols="12" class="parent">
        <p>Ich bin der Parent component</p>
        <button @click="changeDetail" :name.sync="name">Change Details</button>
        <Child v-bind:name="name"></Child>
      </v-col>
    </v-row>
  </v-container>
</template>

<script>
import Child from "./Child";
export default {
  name: "Parent",

  data: () => ({
    name: "test"
  }),
  methods: {
    changeDetail() {
      this.name = "Updated from Parent";
    }
  },
  components: {
    Child
  }
};
</script>

Child:

<template>
  <v-container>
    <v-row class="text-center">
      <v-col cols="12">
        <p>My name is: {{ name}}</p>
        <button @click="resetname">Reset the name</button>
      </v-col>
    </v-row>
  </v-container>
</template>

<script>
export default {
  //   props: ["name"],
  props: {
    name: {
      type: String,
      required: true
    }
  },
  data: () => ({
    newname: "Updated from Child"
  }),
  methods: {
    resetname() {
      this.$emit("update:name", this.newname);
    }
  }
};
</script>

据我在这里阅读:https://vuejs.org/v2/guide/components-custom-events.html#sync-Modifier,我应该使用更新和同步将道具从 child 传回 parent。但是它不起作用。我不明白这里出了什么问题。我错过了什么?

通常最好不要将您的模板绑定到 prop,而是绑定到计算 属性,以确保可以从外部访问和修改数据。它还会稍微简化您的代码,这样您就不必触发更新。

Parent:

<template>
  <v-container>
    <v-row class="text-center">
      <v-col cols="12" class="parent">
        <p>Ich bin der Parent component</p>
        <button @click="changeDetail">Change Details</button>
        <Child v-bind:name.sync="name"></Child>
      </v-col>
    </v-row>
  </v-container>
</template>

<script>
import Child from "./Child";
export default {
  name: "Parent",

  data: () => ({
    name: "test"
  }),
  methods: {
    changeDetail() {
      this.name = "Updated from Parent";
    }
  },
  components: {
    Child
  }
};
</script>

Child:

<template>
  <v-container>
    <v-row class="text-center">
      <v-col cols="12">
        <p>My name is: {{ currentName }}</p>
        <button @click="resetname">Reset the name</button>
      </v-col>
    </v-row>
  </v-container>
</template>

<script>
export default {
  //   props: ["name"],
  props: {
    name: {
      type: String,
      required: true
    }
  },
  data: () => ({
     //Be careful with fat arrow functions for data
     //Because the value of *this* isn't the component, 
     //but rather the parent scope.
  }),
  computed: {
    currentName: {
        get() { return this.name },
        set(value) { this.$emit("update:name", value); }
    }
  },
  methods: {
    resetname() {
      this.currentName = "updated from child";
    }
  }
};
</script>