首页 > 解决方案 > Vue: component failed to update $parent

问题描述

I want to update $parent data from child component. (I know it's bad but very conv for tightly bound component).

So I'm trying like is shown below, but it update field named 'undefined' instead:

Vue.config.productionTip = false;

const child = {
  template: `
    <div class="hello">
      <input type="text" v-model="$parent.obj[this.field]">
      <pre>{{ $props }}</pre>
    </div>`,

  props: ['field'],
}

new Vue({
  el: "#app",

  components: {
    child,
  },

  data() {
    return {
      obj: {
        f1: 111,
        f2: 222
      }
    }
  },

});
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>

<div id="app">
  parent:
  <pre>{{ $data }}</pre>
  
  <hr>
  
  child:
  <child field="f1" />
</div>

标签: javascriptvue.jsvuejs2vue-component

解决方案


You added this keyword to the property of $parent.obj. You don't need to use this keyword in template. Here is the working code: codesandbox


推荐阅读