vue js同步修改器不会更新输入值

时间:2020-04-09 16:15:42

标签: vue.js vuejs2 vue-component

我对vuejs中的同步修饰符有初学者的疑问。在我的示例中,我想根据焦点事件更改输入的值。该值是一个对象inputsData,我正在从app获取它。在parent中,我将其传递到正在渲染的child处。我设置了一个计时器,因为我想发出服务器请求。正如您在handleFocusFromChild方法中看到的那样,它用dataToBeChangednewData更改为{{4秒后也会记录一次)。正如我从vue guid所了解的那样,它还应该更新输入值,但它不会更新,而且我也不明白为什么,因为dataToBeChanged现在有了newData中的新值。有人可以向我解释为什么以及如何使它起作用吗?

我在这里使用父母:

import Parent from "./parent.js";

Vue.component("app", {
  components: {
    Parent
  },
  template: `
           <div>
             <parent :inputsData="{
                                   'firstElement':{'firstInputValue':'Hi there'},
                                   'secondElement':{'secondInputValue':'Bye there'}
                                    }"></parent>
           </div>
            `
});


这是父母:

import Child from "./child.js";
export default {
  name: "parent",
  components: {
    Child
  },
  props: {
    inputsData: Object
  },
  template: ` 
         <div>
           <child @focusEvent="handleFocusFromChild"
                  :value.sync="inputsData.firstElement.firstInputValue"></child>
           <child @focusEvent="handleFocusFromChild"  
                  :value.sync="inputsData.secondElement.secondInputValue"></child>
           </div>
            `,
  computed: {
    dataToBeChanged: {
      get: function() {
        return this.inputsData;
      },
      set: function(newValue) {
        this.$emit("update:inputsData", newValue);
      }
    }
  },
  methods: {
    handleFocusFromChild: function() {
      var newData = {
        firstElement: { firstInputValue: "Hi there is changed" },
        secondElement: { secondInputValue: "Bye there is changed" }
      };
      setTimeout(function() {
        this.dataToBeChanged = newData;
      }, 3000);

      setTimeout(function() {
        console.log(this.dataToBeChanged);
      }, 4000);
    }
  }
};

这是孩子:

export default {
  template: `
              <div class="form-group">
                <div class="input-group">
                  <input @focus="$emit('focusEvent', $event)"
                         v-model="value">
                </div>
              </div>
            `,
  props: {
    value: String
  }
};

1 个答案:

答案 0 :(得分:3)

您的子组件应发出“ this。$ emit('update:value',newValue)”作为事件 看一下文档:https://br.vuejs.org/v2/guide/components-custom-events.html

还有一种方法是这样的:

export default {
  template: `
              <div class="form-group">
                <div class="input-group">
                  <input @focus="$emit('focusEvent', $event)"
                         v-model="valueProp">
                </div>
              </div>
            `,
  props: {
    value: String
  },
  computed: {
    valueProp:{
            get(){
                return this.value
            },

            set(val){
                return this.$emit("update:value", val);
            }
        },
  }
  methods: {
    handleFocus() {
      this.$emit("focusEvent");
    }
  }
};