【问题标题】:how to update vuejs component from parent如何从父级更新 vuejs 组件
【发布时间】:2017-06-18 10:17:44
【问题描述】:

我对 VueJs 有点迷茫,我尝试用组件和 Vue 更新的数据制作一个 vue。

我了解如何使用 $emit 更新父值。

如果可以的话,有人可以打电话吗

HTML 代码

<div id="app2" v-cloak>
  <p>{{labels.lbl1}}: {{values.value}}</p>
  how direct set {{labels.lbl1}} here: <input type="text" v-model:value="values.value"> can set the child value?
  <hr/>
  <child2 v-model:value="values.value" v-bind:lbl="labels.lbl1"></child2>
</div>

<template id="child2">
  <div>
     Set {{internallbl1}} in child:
     <input type="text" v-model="internalValue" >
     <p>Value : {{value}}</p>
  </div>
</template>

JS代码:

Vue.component('child2', {
  template: '#child2',

  //The child has a prop named 'value'. v-model will automatically bind to this prop
  props: ['value','lbl'],
  data: function() {
    return {
      internalValue: '',
      internallbl1:''
    }
  },
  watch: {
    'internalValue': function() {
      // When the internal value changes, we $emit an event. Because this event is 
      // named 'input', v-model will automatically update the parent value
      this.$emit('input', this.internalValue);
    }
  },
  created: function() {
    // We initially sync the internalValue with the value passed in by the parent
    this.internalValue = this.value;
    this.internallbl1 = this.lbl;
  }
});
new Vue({
  el: '#app2',
  data: {
    labels : {lbl1:'Parent value 1'},
    values : {value: 'hello'},
  }
});

这里是 jsFiddle:https://jsfiddle.net/davidhequet/ag0thqar/5/

谢谢你, 大卫

【问题讨论】:

    标签: vue.js mutation


    【解决方案1】:

    我的理解是,internalValue 不会在父级中的值发生变化时发生变化。您可以在value 上设置一个观察者,并在它发生变化时设置internalValue,如下所示:

    Vue.component('child2', {
      template: '#child2',
      ...
      ...
      ...
      created: function() {
        // We initially sync the internalValue with the value passed in by the parent
        this.internalValue = this.value;
        this.internallbl1 = this.lbl;
      },
      watch: {
        'internalValue': function() {
          // When the internal value changes, we $emit an event. Because this event is 
          // named 'input', v-model will automatically update the parent value
          this.$emit('input', this.internalValue);
        },    
         value: function(newVal) {
            this.internalValue = newVal
         }
      },
    });
    

    查看工作fiddle

    【讨论】:

      猜你喜欢
      • 2021-07-30
      • 2017-04-16
      • 1970-01-01
      • 2017-12-31
      • 2017-09-04
      • 1970-01-01
      • 2018-07-20
      相关资源
      最近更新 更多