使用$ parent更改父组件变量的值,但未反映在vuejs中的插值语法中

时间:2018-12-13 05:51:51

标签: javascript vue.js

Child component
<template>
  <div>
    <h3>Child Component</h3>
  <div>
         <button   @click="changeValue()">change Parent </button>
   </div>
 </div>
</template>

<script>
export default {
 data() {
    return{}
 },
 methods: {
  changeValue() {
    this.$parent.model[somekey] = somevalue
  }
 }
</script>

<style>

</style>

父项

<template>
  <div>
    <h3>Parent Component</h3>
   <div>
      {{model}} **<!--value is not refleted here -->**
  </div>
  </div>
</template>

<script>
export default {
  data() {
    return{
     model: {}
    }
  }
 }
</script>

<style>

</style>

使用子组件的changeValue方法更改父变量的值,但未反映在父插值语法({{model}})中。但是当我使用父方法访问时,我得到了更新的值。

2 个答案:

答案 0 :(得分:0)

Vue无法检测何时向对象添加或删除属性。阅读Change Detection Caveats

预先定义属性:

data: {
  model: {
    foo: null
  }
}
this.$parent.model.foo = somevalue

如果需要动态添加属性,则需要使用Vue.set

答案 1 :(得分:0)

您应该从子级发出事件并在父级中处理,而不是直接在子级中更改它。您可以更轻松地管理数据

例如

子组件

<template>
  <div>
    <h3>Child Component</h3>
  <div>
         <button @click="changeValue()">change Parent </button>
   </div>
 </div>
</template>

<script>
export default {
 data() {
    return{}
 },
 methods: {
  changeValue() {
    this.$emit('changeValue', someValue)
  }
 }
</script>

父组件

<template>
  <div>
    <h3>Parent Component</h3>
   <div>
      {{model}}
  </div>
  <child-component @changeValue="changeValue" />
  </div>
</template>

<script>
export default {
  data() {
    return{
     model: {}
    }
  },
  methods: {
    changeValue (newValue) {
      this.model[someKey] = newValue
      this.model = JSON.parse(JSON.stringify(this.model))
    }
  }
 }
</script>