首页 > 解决方案 > Vuejs 3 在组件中单击更改数据

问题描述

我创建了一个这样的组件:

卡组件:

<template>  
   <div> 
      <svg v-if="like.find(e=>e==product.p_id)" @click='likes(product.p_id)' xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-gray-400 cursor-pointer" fill='#c30' viewBox="0 0 24 24" stroke='#c30'>
           <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
      </svg>
      <svg v-else @click='likes(product.p_id)' xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-gray-400 cursor-pointer" fill='none' viewBox="0 0 24 24" stroke='currentColor'>
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
      </svg>
   </div>
</template>
    data() {
        return {
            like: [],
        }
    },
    methods:{
        likes(id){
            let keys = Object.keys(localStorage);
            for(let key of keys) {
                this.like.push(localStorage.getItem(key));
            }
            if(!this.like.includes(id.toString())){
                this.like.push(id);
                localStorage['likes' + id] = id
            }else{
                localStorage.removeItem('likes' + id)
                this.like.splice(this.like.indexOf(id))
            }
        }
    },
    mounted() {
        let keys = Object.keys(localStorage);
            for(let key of keys) {
                this.like.push(localStorage.getItem(key));
            }
    },

Home 组件中,我使用了Card 组件两次,问题出在Card 组件中的Click 事件上,当我单击它时,它仅在一个组件中发生变化,并且在重新加载页面后,它应用了更改。

家庭组件:

<card :product="ProdLastest" />
<card :product="Hotest" />

标签: vue.js

解决方案


我通过使用Vuex找到了解决方案

我只是存储数据值(like),然后将其从存储状态附加到 Card 组件中


推荐阅读