Vue.js从父内部更新子组件数据

时间:2018-09-11 08:32:15

标签: javascript vue.js vuejs2

如何从父级内部更新子级组件中的数据?我正在尝试从父级内部更新autores属性,并让其更新子级数据。目前没有任何反应,我认为我没有正确链接数据。如果我将其作为数据添加到父级组件中,则在代码运行时父级会重新渲染,并且看不到结果。

父母:

<template>
    <div>
        <input @keyup="editName(lender.id, $event)">

            <autocomplete-suggestions :autores="[]"></autocomplete-suggestions>

    </div>
</template>

<script type="text/javascript">
    export default {
        props: ['lender'],

        data(){
            return {

            }
        },

        methods: {
            editName: function(lenderid, event) {

                var self = this;

                    axios.post('/lenders/autocomplete', {...})
                        .then(function (data) {

                            self.autores = data.data.suggestions;

                        })
                        .catch(function (error) {
                            console.log("Error occurred getting the autocomplete");
                        });


            },
        },
        watch: {

        },
        mounted: function() {

        }
    };
</script>

孩子:

<template>
    <div class="list">
        <div v-for="(res, i) in autores">{{res}}</div>
    </div>
</template>

<script type="text/javascript">
    export default {
        props: ['autores'],
        data(){
            return {

            }
        }
    };
</script>

更新

如果我将父代码更改为:

data(){
    return {
        autores:[]
    }
},

和:

<autocomplete-suggestions :autores="autores"></autocomplete-suggestions>

然后,只要我更新this.autores,就会在重置时将任何文本键入到父级的文本框中,就像重新渲染整个组件一样。如何停止?

1 个答案:

答案 0 :(得分:1)

父母:

<template>
  <div>
    <input @keyup="editName(lender.id, $event)">
    <autocomplete-suggestions ref="autocompleteSuggestions"></autocomplete-suggestions>
  </div>
</template>

<script type="text/javascript">
  export default {
    props: ['lender'],
    methods: {
      editName: function (lenderid, event) {
        var self = this;
        axios.post('/lenders/autocomplete', {...})
          .then(function (data) {
            self.$refs.autocompleteSuggestions.autores = data.data.suggestions;
          })
          .catch(function (error) {
            console.log("Error occurred getting the autocomplete");
          });
      },
    },
  };
</script>

孩子:

<template>
  <div className="list">
    <div v-for="(res, i) in autores">{{res}}</div>
  </div>
</template>

<script type="text/javascript">
export default {
  data() {
    return {
      autores: []
    };
  },
};
</script>