Vuejs:如何将数据传递给不相关的组件?

问题描述 投票:0回答:1
javascript vue.js vuejs3 store pinia
1个回答
0
投票

是的,因为您已经使用 Pinia,所以您可以创建一个可由“ItemCard”和“ViewRecipeDetail”访问的共享状态。

创建存储和操作来设置选定的食谱数据:

// storeRecipe

import { defineStore } from 'pinia';
    export const useStoreReceipe = defineStore('recipe', {
      state: () => ({
        selectedRecipe: null,
      }),
      actions: {
        setSelectedRecipe(recipe) {
          this.selectedRecipe = recipe;
        },
        clearSelectedRecipe() {
          this.selectedRecipe = null;
        },
      },
    });

单击 router-link 时调度操作以设置所选配方:

// ItemCard.vue

<script setup>
import { useRecipeStore } from '@/store/recipeStore';
const recipeStore = useRecipeStore();

const handleClick = () => {
  recipeStore.setSelectedRecipe(props.data);
};
</script>

<router-link
  class="card__link"
  :to="{ name: 'recipeDetail', params: { recipe: data.slug } }"
  @click="handleClick"
>
  View more
</router-link>

从商店检索所选食谱:

// ViewRecipeDetail.vue

<script setup>
import { useRecipeStore } from '@/store/recipeStore';
const recipeStore = useRecipeStore();

const selectedRecipe = computed(() => recipeStore.selectedRecipe);
</script>

<template>
  <div v-if="selectedRecipe">
    <img class="card__image" :src="getSrc('.jpg')" :alt="selectedRecipe.alt" />

    <div class="card__content">
      <h2 class="card__title">{{ selectedRecipe.title }}</h2>
      <p class="card__text">{{ selectedRecipe.short_description }}</p>
    </div>
  </div>
</template>
© www.soinside.com 2019 - 2024. All rights reserved.