如何在Vue JS中将父组件的更新值发送到子组件?

Rav*_*arg 16 vue.js vue-component vuejs2

我通过props将一个变量从父组件传递给子组件.但是通过一些操作,该变量的值会发生变化,即点击父组件中的某个按钮,但我不知道如何将更新后的值传递给child?假设一个变量的值最初为false,并且父组件中有"编辑"按钮.我在单击"编辑"按钮时更改此变量的值,并希望将更新后的值从父组件传递给子组件.

小智 16

在父组件和子组件之间使用道具时,应该动态更新属性的值.根据您的示例并且属性的初始状态为false,可能是该值未正确传递到子组件.请确认您的语法是否正确.你可以在这里查看参考.

但是,如果要在属性值发生更改时执行一组操作,则可以使用观察程序.

编辑:

下面是使用的例子道具和观察家:

HTML

<div id="app">
    <child-component :title="name"></child-component>
</div>
Run Code Online (Sandbox Code Playgroud)

JavaScript的

Vue.component('child-component', {
  props: ['title'],
  watch: {
    // This would be called anytime the value of title changes
    title(newValue, oldValue) {
      // you can do anything here with the new value or old/previous value
    }
  }
});

var app = new Vue({
  el: '#app',
  data: {
    name: 'Bob'
  },
  created() {
    // changing the value after a period of time would propagate to the child
    setTimeout(() => { this.name = 'John' }, 2000);
  },
  watch: {
    // You can also set up a watcher for name here if you like
    name() { ... }
  }
});
Run Code Online (Sandbox Code Playgroud)


Lak*_*eri 8

您可以使用vue手表观看(道具)变量.

例如:

<script>
export default {
  props: ['chatrooms', 'newmessage'],
  watch : {
    newmessage : function (value) {...}
  },
  created() {
    ...
  }
}
</script>
Run Code Online (Sandbox Code Playgroud)

我希望这能解决你的问题.:)


Gus*_*ube 6

值是对象的属性可能特别棘手。如果更改该对象中的属性,状态不会更改。因此,子组件不会更新。

检查这个例子:

// ParentComponent.vue

<template>
    <div>
        <child-component :some-prop="anObject" />
        <button type="button" @click="setObjectAttribute">Click me</button>
    </div>
</template>

<script>
    export default {
        data() {
            return {
                anObject: {},
            };
        },
        methods: {
            setObjectAttribute() {
                this.anObject.attribute = 'someValue';
            },
        },
    };
</script>
Run Code Online (Sandbox Code Playgroud)
// ChildComponent.vue

<template>
    <div>
        <strong>Attribute value is:</strong>
        {{ someProp.attribute ? someProp.attribute : '(empty)' }}
    </div>
</template>

<script>
    export default {
        props: [
            'someProp',
        ],
    };
</script>
Run Code Online (Sandbox Code Playgroud)

当用户单击“Click me”按钮时,本地对象将被更新。然而,由于对象本身是相同的——只是它的属性发生了变化——所以不会调度状态更改。

要解决这个问题,setObjectAttribute可以这样更改:

setObjectAttribute() {

    // using ES6's spread operator
    this.anObject = { ...this.anObject, attribute: 'someValue' };

    // -- OR --

    // using Object.assign
    this.anObject = Object.assign({}, this.anObject, { attribute: 'someValue' });

}
Run Code Online (Sandbox Code Playgroud)

通过这样做,anObject数据属性正在接收新的对象引用。然后,状态发生更改,子组件将接收该事件。


小智 5

您可以使用动态道具。

这将根据需要将数据从父组件动态传递到子组件。