Home > Enterprise >  How can add a button to to search bar and keep the keypress - VUE
How can add a button to to search bar and keep the keypress - VUE

Time:04-07

My search is working, but I need to press enter key to have results. I want to add the option of having results with a button too. Search for results by pressing enter or clinking button. Can anyone help me?

<div >
    <input 
      type="text" 
       
      placeholder="Search..."
      v-model="query"
      @keypress="fetchWeather"
    />
   <button>Click Me!</button>
  </div>

    methods: {
        fetchWeather (e) {
          if (e.key == "Enter") {
            fetch(`${this.url_base}weather?q=${this.query}&units=metric&APPID=${this.api_key}`)
              .then(res => {
                return res.json();
              }).then(this.setResults);
          }
        },
        setResults (results) {
          this.weather = results;
        }

CodePudding user response:

You can use @keyup.enter="fetchWeather" for input, and @click="fetchWeather" for button.

CodePudding user response:

Try this :

new Vue({
  el: '#app',
  data: {
    query: null,
    queryData: ['search1', 'search2', 'search3', 'search4'],
    searchedData: []
  },
  mounted() {
    this.searchedData = [...this.queryData]
  },
  methods: {
    fetchWeather() {
      if (!this.query) return;
      this.searchedData = this.queryData.filter(item => item.includes(this.query))
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <input 
         type="text" 
          
         placeholder="Search..."
         v-model="query"
         @keyup.enter="fetchWeather"
         />
  <button @click="fetchWeather">Click Me!</button>
  
  <ul>
    <li v-for="(item, index) in searchedData" :key="index"> {{ item }} </li>
  </ul>
</div>

CodePudding user response:

It should be working fine if you just add @click="fetchWeather" inside the button tag, like this:

<button @click="fetchWeather">Click me"

  • Related