简体   繁体   中英

Automatically update the input field within a form, vue.js

I want to search for elements using an input field within a form. I am passing a value from a component to another and the content changes but only after pressing enter. Is there a way to automatically update the list, after every new letter is typed? Here is my code:

Parent(App):

<template>
  <div id="app">
    <Header v-on:phrase-search="passPhrase" />
  </div>
</template>

<script>
import Header from ...

export default {
  name: "App",
  components: {
    Header,
  },
  data() {
    return {
      posts: [],
      searchedPhrase: ""
    };
  }
  computed: {
    filteredPosts() {
      let temp_text = this.searchedPhrase;
      temp_text.trim().toLowerCase();

      return this.posts.filter(post => {
        return post.name.toLowerCase().match(temp_text);
      });
    }
  },
  methods: {
    passPhrase(phrase) {
      this.searchedPhrase = phrase;
    }
  }
};
</script>

Child(Header):

<template>
<div class="child">
  <p>Search:</p>
    <form @submit.prevent="phrasePassed">
      <input type="text" v-model="phrase" />
    </form>
</div>
</template>

<script>
export default {
  name: "search",
  data() {
    return {
      phrase: ""
    };
  },
  methods: {
    phrasePassed() {
      this.$emit("phrase-search", this.phrase);
    }
  }
};
</script>

passPhrase() brings the value from the child to the parent and then filteredPosts() find appropriate elements. I suspect that the form might be guilty of this issue but I do not know precisely how to get rid of it and still be able to pass the value to the parent.

Thanks

in the child you use submit event which called on enter. you should use @input on the input itself. and btw you didnt need even to declare pharse in the data because you didnt use it in the child. you just pass it up

you it like so

<template>
  <div class="child">
    <p>Search:</p>
    <form>
      <input type="text" @input="phrasePassed">
    </form>
  </div>
</template>

<script>
export default {
  name: "search",
  methods: {
    phrasePassed(e) {
      this.$emit("phrase-search", e.target.value);
    }
  }
};
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM