vue.js - 如何存储子组件发出的值?
问题描述
从子组件中,我发出一个我希望父组件接收的值。在父组件中,我有一个已启动为 null 的属性,目的是在父组件收到发出的值后更改此值,但由于某种原因它不起作用。
这是代码
子组件:
<template>
<div class="gameComponent">
<b-row>
<b-col>
<h3>{{ game.name }}</h3>
</b-col>
</b-row>
<b-row>
<b-col>
<p>{{ game.platform }}</p>
</b-col>
</b-row>
<b-row>
<b-col>
<b-button @click="viewGameFromLibrary(game)">View Game</b-button>
</b-col>
<b-col>
<b-button @click="removeGameFromLibrary(game.id)">Remove Game</b-button>
</b-col>
</b-row>
</div>
</template>
<script>
import api from '../assets/javascript/api.js'
import ViewGameVue from './ViewGame.vue';
export default {
props:['game'],
methods:{
removeGameFromLibrary(id){
api.removeGameFromLibrary(id);
location.reload();
},
viewGameFromLibrary(game){
this.$emit("viewGame", game)
}
}
}
</script>
<style>
</style>
这是父组件:
<template>
<div class="library">
<ViewGame />
<b-row>
<b-col v-for="game in games" lg="4" xl="4">
<GameInLibrary v-bind:game="game" @viewGame="getGame"/>
</b-col>
</b-row>
</div>
</template>
<script>
import api from '../assets/javascript/api.js'
import GameInLibrary from '@/components/GameInLibrary'
export default {
data(){
return {
games:[],
gameToView:''
}
},
methods: {
getGame(game){
this.gameToView = game
}
},
components:{
GameInLibrary,
ViewGame: ()=> import('./ViewGame')
},
created(){
api.getAllGamesFromLibrary(this.games)
}
}
</script>
<style>
</style>
this.gameToView = 游戏好像不行,有什么办法吗?
解决方案
既然你跑console.log(game)
进去getGame()
了,它显示了预期的值,这意味着发出game
的值不是未定义的,它实际上被分配给了this.gameToView
,那么有什么问题呢?
game
因此,您的父组件从一个子组件接收发出的值。
如果您随后需要将此值从父组件发送到另一个子组件:<ViewGame/>
您只需要像这样传递它:
父组件:
<div class="library">
<ViewGame :gameToView="gameToView"/>
...
</div>
子组件ViewGame
:
<div>{{gameToView}}</div>
...
props: ['gameToView']
推荐阅读
- javascript - 尝试创建一个使输入加倍的按钮
- discord - discord bot可以加入频道但不能播放音乐
- r - 一个命令中的逐行正态性、偏度和峰度
- django - 浏览器在重新加载 Angular 网页后进行 HTTP 调用
- mysql-error-1064 - 你会帮我吗?我不断收到错误代码 1064,我不明白为什么
- json - 我只需要从 api 获取文本标题和文本描述
- office365 - 无法在 C# 错误中在 Office 365 中发送电子邮件
- sybase - 需要使用查询从“aaaa-h0321456-f7894-1599-5”获取第一个破折号和第二个破折号之间的值
- php - CSS 不适用于 WordPress 下 WooCommerce 中的媒体查询
- angular - 在 Angular 中的同一组件之间制作动画