簡體   English   中英

正在傳遞道具但不更新組件

[英]Prop being passed but not updating the component

所以我有一個名為 updateAll(data.items) 的 function,它應該采用數組並隨機分配一個新名稱,當我在 vue 開發工具中查看時,data.items 似乎正在更新並被傳遞給組件但實際上並沒有更新瀏覽器

我還在我的 buildData.js 中添加了它用於同一個應用程序,但在反應中,我試圖盡可能地保持它的通用性

//HomeView.vue

<script setup>
import { reactive, watch } from "vue";
import Hero from '@/components/Hero.vue'
import FunctionButton from '@/components/FunctionButton.vue'
import ItemsContainer from '@/components/ItemContainer.vue';
import * as dataFunc from '@/data/buildData'

const data = reactive({
  items: JSON.parse(localStorage.getItem('items')) || []
})

console.log(data.items)

watch(() => data.items,(newValue) => {
  localStorage.setItem('items', JSON.stringify(newValue))
}, {deep: true});


</script>

<template>
    <div class='w-2/3 mx-auto text-center'>
      <Hero HeroText="The one stop shop to store recipes!" />
      <main>
        <h1 class="text-5xl font-extrabold dark:text-white">Recipe Manager</h1>
        <div class='functions gap-4 grid grid-cols-2 md:grid-cols-3 mt-8 mx-auto w-fit'>
          <FunctionButton name="Add new recipe" @click="() => data.items = [...data.items,...dataFunc.buildData(1)]"/>
          <FunctionButton name="Add 100 recipes" @click="() => data.items = [...data.items,...dataFunc.buildData(100)]"/>
          <FunctionButton name="Add 1000 recipes" @click="() => data.items = [...data.items,...dataFunc.buildData(1000)]"/>
          <FunctionButton name="Delete all recipes" @click="() => data.items = dataFunc.deleteAll()"/>
          <FunctionButton name="Edit all recipes" @click="() => data.items = dataFunc.updateAll(data.items)"/>
        </div>
        <ItemsContainer :items="data.items"/>
      </main>
    </div>
</template>

//ItemContainer.vue

<script setup>
import Item from '@/components/Item.vue';

const props = defineProps({
  items: {type: Array, default: () => []},
})
</script>

<template>
    <div
        class='items-container w-full md:w-max bg-gray-800 dark:bg-gray-800 text-white dark:text-black mx-auto mt-12 p-4 space-y-4'>
        <Item
          v-for="item in items"
          v-if="items.length > 0"
          :key="item.id"
          :meal="item"
        /> 
        <p v-else class='text-white'>No items to display</p>
    </div>
</template>

我試圖讓它盡可能通用,就像試圖在 Vue 和 React 上制作一個類似的應用程序,這樣他們就可以分享這個

import { v4 as uuidv4 } from 'uuid';

function create(){
    const data = {
        id: uuidv4(), 
        category: category[random(category.length)],
        name: meals[random(meals.length)], 
        prepTime: randomTime(),
        cookTime: randomTime(), 
        isFav: false
    }
    return data
}

function random(max){
    return Math.round(Math.random() * 1000) % max;
}

const meals = [
    "Roast Chicken", "Omelette", "Steak Pie", "Beef Stir Fry", "Fish And Chips", "Tomato And Prawn Risotto", "Pepperoni Pizza", "Cheesy Nachos", "Fajitas", "Baked Potato",
    "Full English Breakfast", "Pancakes", "Chocolate Brownies", "Meatballs With Red Pepper Sauce", "Chicken Cesar Salad", "Beef Burger", "Chips","Macaroni Cheese", "Fillet Steak", "Chicken Wings", 
    "BBQ Ribs", "Tomato Soup", "Prawn Dim Sum", "Pork Gyozas", "Tomato Bruschetta", "Spring Rolls", "Beef Jerky", "Lasagne", "Spagetti Carbonara", "Salmon And Potatoes"
]

const category = [
    "Breakfast", "Lunch", "Dinner"
]

function randomTime(){
    return Math.round(Math.random() * 30)
}

function buildData(count){
    const data = new Array(count);
    for(let i = 0; i<count; i++){
        data[i] = create();
    }
    return data;
}


function updateAll(currentArray){
    return currentArray.map((item) => {
        return{...item, name: meals[random(meals.length)], }
    })
}

function updateOne(item){
    return{...item, name: meals[random(meals.length)], }
}

function favouriteAll(currentArray = []){
    return currentArray.map((item) => {
        return {...item, isFav: true}
    })
}

function deleteAll(){
    const data = []
    return data;
}

export {buildData, deleteAll, favouriteAll, updateAll, updateOne};

檢查控制台是否有錯誤。

如果我從HomeView.vue 、你的ItemContainer.vueItem.vue (你沒有提供)中獲取功能,那么它就可以工作。

檢查正在運行的Vue SFC Playground

代碼:

App.vue

<script setup>
import { ref, watch, reactive } from 'vue'
import ItemsContainer from './ItemContainer.vue';

const data = reactive({
  items: []
})

console.log(data.items)

watch(() => data.items, (newValue) => {
  alert(JSON.stringify(newValue))
}, {deep: true});
  
const addItem = () => {
    data.items.push({ id: data.items.length, name: 'New Item'})
}  
  
</script>

<template>
    <ItemsContainer :items="data.items"/><br />
  <button type="button" @click="addItem()">Add</button>    
</template>

ItemContainer.vue是一樣的。

Item.vue

<script setup>
const props = defineProps({
  meal: {
    type: Object, 
    default: {undefined}
  }
})
</script>

<template>
    <div>
         {{JSON.stringify(meal)}}<br />
    </div>
</template>

更新

我已經用你的函數更新了playground ,它仍然運行良好。 問題出在別處。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM