观看动态子组件Vue

时间:2019-06-04 11:15:57

标签: vue.js vuejs2 vue-component

我有一个Vue.js组件,该组件使用基于父项的prop的for循环来呈现多个类似的组件。我有一个使用vue-bootstrap-typeahead在父级中工作的typeahead字段。示例NPM。我还希望在每个组件中输入一个。我相信下面的示例代码已经结束,但是我不知道如何正确观察子组件。我有两个伪编码的典范。谁能提供指导?

<template>
  <div>
    <div v-for="(indivComp, eventIndex) in indivComps" :key="eventIndex">
      <vue-bootstrap-typeahead
        v-model="indivComp.typeahead"
        :data="options.value"
        :serializer="item => item.name"
        @hit="$event => {indivComp.typeahead = $event.name;}"
        placeholder="Enter a value..."
      />
    </div>
  </div>
</template>

<script>
import options from "../options.json";

export default {
  props: { parent: Array },
  data() {
    return {
      indivComp: this.parent,
      options: options
    };
  },
  methods: {
    getTypeahead(category, query) {
      this.options[category] = [];
      axios
        .get(`${process.env.search}search?search_term=${query}`)
        .then(res => {
          res.data.items.forEach(element => {
            this.options[category].push(element);
          });
        })
        .catch(error => {
          console.log(error);
        });
    }
  },
  //option 1
  mounted() {
    this.$watch("$refs.indivComp.typeahead", 
      function(query) {
        this.getTypeahead(query);
      }
    );
  },
  //option 2
  watch: {
    indivComp.typeahead: function(query) {
      this.getTypeahead(query);
    }
  };
};
</script>

0 个答案:

没有答案