vue.js - 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" />
解决方案
我通过使用Vuex找到了解决方案
我只是存储数据值(like),然后将其从存储状态附加到 Card 组件中
推荐阅读
- javascript - 在角度的循环依赖中访问模块导出的不存在的属性“lineno”
- java - Spring JPA 一对一映射可以允许保存更多项目
- gatsby - 盖茨比中 Chakra-ui 的扩展主题
- python - 使用reduce方法的斐波那契数列
- augmented-reality - 在 HTTPS 网站上的 Web AR(模型查看器)上播放音频/声音?
- c++ - 我可以在类中初始化引用吗?(也许在构造函数中?)
- c - 奇怪的编译问题
- android - LiveData 封装如何在 AndroidStudio 和 Kotlin 中工作?
- python - 用列表理解替换 for 循环
- javascript - 如何通过javascript获取FB帖子链接?