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

时间:2019-12-15 21:32:05

标签: vue.js vuejs2 vue-component vue-cli

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

1 个答案:

答案 0 :(得分:3)

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

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

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

父项:

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

子组件ViewGame

<div>{{gameToView}}</div>
...
props: ['gameToView']