首页 > 解决方案 > 如何存储子组件发出的值?

问题描述

从子组件中,我发出一个我希望父组件接收的值。在父组件中,我有一个已启动为 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.jsvuejs2vue-componentvue-cli

解决方案


既然你跑console.log(game)进去getGame()了,它显示了预期的值,这意味着发出game的值不是未定义的,它实际上被分配给了this.gameToView,那么有什么问题呢?

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

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

父组件:

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

子组件ViewGame

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

推荐阅读