首页 > 解决方案 > Vue中的两种数据绑定:无法从子组件更新父组件

问题描述

我得到以下两个组件:

家长:

<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>

孩子:

<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 ,我应该使用更新和同步将道具从孩子传递回父母。但是它不起作用。我不明白这里出了什么问题。我错过了什么?

标签: javascriptvue.jstwo-way-binding

解决方案


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

家长:

<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>

孩子:

<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>

推荐阅读