如何在Vue JS中将更新的值从父组件发送到子组件? [英] How to send updated values from Parent component to child component in Vue JS?

查看:26
本文介绍了如何在Vue JS中将更新的值从父组件发送到子组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

解决方案

在父组件和子组件之间使用 props 时,您的属性值应该动态更新.根据您的示例和属性的初始状态为 false,该值可能未正确传递到子组件中.请确认您的语法正确.您可以查看此处以供参考.

但是,如果您想在属性值发生变化时执行一组操作,则可以使用 观察者.

这是一个使用道具和观察者的例子:

HTML

<child-component :title="name"></child-component>

JavaScript

Vue.component('child-component', {道具:['标题'],手表: {//这将在 title 的值发生变化时调用标题(新值,旧值){//您可以在此处使用新值或旧/先前值执行任何操作}}});var app = new Vue({el: '#app',数据: {名称:'鲍勃'},创建(){//一段时间后更改值将传播到子项setTimeout(() => { this.name = 'John' }, 2000);},手表: {//如果你愿意,你也可以在这里为 name 设置一个 watcher姓名() { ... }}});

I am passing a variable from parent component to child component through props. But with some operation, the value of that variable is getting changed i.e. on click of some button in parent component but I did not know how to pass that updated value to child? suppose the value of one variable is false initially and there is Edit button in parent component. i am changing the value of this variable on click of Edit button and want to pass the updated value from parent to child component.

解决方案

Your property's value should be updated dynamically when using props between parent and child components. Based on your example and the initial state of the property being false, it's possible that the value was not properly passed into the child component. Please confirm that your syntax is correct. You can check here for reference.

However, if you want to perform a set of actions anytime the property's value changes, then you can use a watcher.

EDIT:

Here's an example using both props and watchers:

HTML

<div id="app">
    <child-component :title="name"></child-component>
</div>

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() { ... }
  }
});

这篇关于如何在Vue JS中将更新的值从父组件发送到子组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆