簡體   English   中英

Vue中的兩種數據綁定:無法從子組件更新父組件

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

我得到以下兩個組件:

家長:

<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://v2.vuejs.org/v2/guide/components-custom-events.html#sync-Modifier ,我應該使用更新和同步將道具從孩子傳遞回父母。 但是它不起作用。 我不明白這里出了什么問題。 我錯過了什么?

通常最好不要將模板綁定到道具,而是綁定到計算屬性,以確保在外部訪問和修改數據。 它還將稍微簡化您的代碼,以便您不必觸發更新。

家長:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM