我如何存储子组件的发射值?

问题描述 投票:1回答:1

[从子组件中,我发出了一个我希望父母接收的值。在父组件中,我有一个已初始化为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 =游戏似乎无法正常工作,我能做些什么吗?

vue.js vuejs2 vue-component vue-cli
1个回答
3
投票

由于您在console.log(game)内部运行了getGame()并且显示了预期值,这意味着发出的game值不是未定义的,并且实际上已分配给this.gameToView,所以出了什么问题?

因此,您的父组件从一个子组件接收发射值game

如果您随后需要将此值从父级发送到另一个子级组件:<ViewGame/>,则只需要像这样传递它:

父组件:

<div class="library">
  <ViewGame :gameToView="gameToView"/>
  ...
</div>

子组件ViewGame

<div>{{gameToView}}</div>
...
props: ['gameToView']
© www.soinside.com 2019 - 2024. All rights reserved.