Home > database >  communication between components in vuejs. (search field)
communication between components in vuejs. (search field)

Time:09-21

well i'm new to vue js and developing an application with a search function.

This is my component where the search results will be rendered.

<script>
import RecipeItem from "../recipe/RecipeItem";
import { baseApiUrl } from "@/global";
import axios from "axios";
import PageTitle from "../template/PageTitle";

export default {
  name: "Search",
  components: { PageTitle, RecipeItem },
  data() {
    return {
      recipes: [],
      recipe: {},
      search: '', 
    }
  },
  methods: {
    getRecipes() {
      const url = `${baseApiUrl}/search?search=${this.search}`;
      axios(url).then((res) => {
        this.recipes = res.data;
      });
    }
  },
  watch: {
    search() {
      const route = {
        name: 'searchRecipes'
      }
      if(this.search !== '') {
        route.query = {
          search: this.search
        }
      }
    },
    '$route.query.search': {
      immediate: true,
      handler(value) {
        this.search = value
      }
    }
  },
};
</script>
<template>
  <div class="recipes-by-category">
    <form class="search">
      <router-link :to="{ path: '/search', query: { search: search }}">
      <input  v-model="search" @keyup.enter="getRecipes()" placeholder="Search recipe" />
      <button type="submit">
        <font-icon class="icon" :icon="['fas', 'search']"></font-icon>
      </button>
      </router-link>
    </form>
    <div class="result-search">  
      <ul>
        <li v-for="(recipe, i) in recipes" :key="i">
          <RecipeItem :recipe="recipe" />
        </li>
      </ul>
    </div>
  </div>
</template>

ok so far it does what it should do, searches and prints the result on the screen. But as you can see I created the search field inside it and I want to take it out of the search result component and insert it in my header component which makes more sense for it to be there. but I'm not able to render the result in my search result component with my search field in the header component.

but I'm not able to render the result in my search result component with my search field in the header component.

Header component

<template>
  <header class="header">
    
    <form class="search">
      <input  v-model="search" @keyup.enter="getRecipes()" placeholder="Search recipe" />
      <router-link :to="{ path: '/search', query: { search: this.search }}">
      <button type="submit">
        <font-icon class="icon" :icon="['fas', 'search']"></font-icon>
      </button>
      </router-link>
    </form>
    
    <div class="menu">
      <ul class="menu-links">
        <div class="item-home">
          <li><router-link to="/">Home</router-link></li>
        </div>
        <div class="item-recipe">
          <li>
            <router-link to="/"
              >Recipes
              <font-icon class="icon" :icon="['fa', 'chevron-down']"></font-icon>
            </router-link>
            <Dropdown class="mega-menu" title="Recipes" />
          </li>
        </div>
        <div class="item-login">
          <li>
            <router-link to="/auth" v-if="hideUserDropdown">Login</router-link>
            <Userdropdown class="user" v-if="!hideUserDropdown" />
          </li>
        </div>
      </ul>
    </div>
  </header>
</template>

Result component

<template>
  <div class="recipes-by-category">
    <div class="result-search">  
      <ul>
        <li v-for="(recipe, i) in recipes" :key="i">
          <RecipeItem :recipe="recipe" />
        </li>
      </ul>
    </div>
  </div>
</template>

CodePudding user response:

Keep the state variables in whatever parent component is common to both the header component and the results component. For example, if you have a Layout component something like this:

<!-- this is the layout component -->
<template>
  <HeaderWithSearch v-on:newResults="someFuncToUpdateState" />
  <ResultsComponent v-bind:results="resultsState" />
</template>
<!-- state and function to update state are in a script here... -->

When the search bar returns results you need to pass that data "up" to the parent component with an $emit call, then the parent component can then pass that state back down to the results component using normal props.

Check out this documentation: https://vuejs.org/v2/guide/components-custom-events.html

Be sure to pay special attention to the .sync part of the documentation and determine if that's something you need to implement as well.

Unless you want to use a more complicated state management library like vuex (which shouldn't be necessary in this case) you can just keep state in a common parent and use $emit to pass up and props to pass down.

  • Related