【问题标题】:Problem with passing data from Vuex getters to child component将数据从 Vuex getter 传递到子组件的问题
【发布时间】:2019-09-19 05:30:24
【问题描述】:

我正在使用 Vue 和 Vuex 创建电影应用程序,它将在 Home 组件中显示所有电影,并单击 Details(子)组件中的单个电影。我在 Home 组件中获取所有电影,但无法在 Details 组件中显示单个电影。

我在子组件中启用了道具,但我在将电影 ID 传递给从 getter(在详细信息组件中)导入的方法时遇到问题,该方法应该从电影列表中过滤选定的电影。

首页组件

<template>
  <div class="home">
     <router-view />
          <h1>Home component:</h1>
            <div v-for="movie in movies"
              :key="movie.id">
              <div>
                <router-link :to="'/movie/' + movie.id">{{ movie.title }}</router-link>
              </div>
            </div>
  </div><!--home-->
</template>

<script>
import axios from 'axios'
import { mapGetters, mapActions } from 'vuex'

export default {
  name: "home",
  methods: {
        ...mapActions(['fetchMovies']),
    },
    computed: {
        ...mapGetters(['movies'])
    },
    created() {
        this.fetchMovies()
    }
};
</script>

细节组件

<template>
    <div>
        <h1>Movie details - child component</h1>
        <h2>Title: {{ movie.title }}</h2>
    </div>
</template>

<script>
import { mapGetters } from 'vuex'
    export default {
        props: ['id'],
        computed: {
            movie() {
                return this.$store.getters.singleMovie(this.id)
            }
        }
    }
</script>

Vuex 商店

const state = {
  movies: []
};
const getters = {
  movies: state => state.movies,
  singleMovie: state => movieId => {
    return state.movies.find(item => item.id === movieId);
  }
};
const actions = {
  async fetchMovies({ commit }) {
    const response = await axios.get(
      movie_url + "movie/popular" + "?api_key=" + api_key
    );
    commit("setMovies", response.data.results);
  }
};
const mutations = {
  setMovies: (state, items) => (state.movies = items)
};
export default {
  state,
  getters,
  actions,
  mutations
};

我尝试将 {{movie.title}} 替换为 {{id}},然后在单击 Home 组件中列出的电影时显示电影 ID。我还尝试将电影 ID 硬编码为参数:return this.$store.getters.singleMovie(299536) 并成功显示标题,但在控制台中出现错误“TypeError:无法读取未定义的属性'title'”。显然我在传递传递的电影 ID 时犯了错误。

【问题讨论】:

    标签: vue.js vuex vue-router


    【解决方案1】:

    您的计算属性影片不会在每个 vue 生命周期中加载。所以,在你第一次得到movie时,它是undefined,而你的小胡子{{ movie.title }}实际上类似于{{ 'undefined'.title }},这会导致错误。

    要解决这个问题,您既可以在template 中添加一个v-if="movie" 条件,也可以在计算属性movie 中返回一个默认值。像这样,例如:return state.movies.find(item =&gt; item.id === movieId) || {};

    【讨论】:

    • Matheus,我尝试在我的代码中应用您的建议,但没有成功 :(。您能否更具体地说明我的代码应该如何实现这项工作,谢谢。
    猜你喜欢
    • 1970-01-01
    • 2021-01-20
    • 2019-06-11
    • 1970-01-01
    • 2019-02-27
    • 2017-04-20
    • 2017-10-03
    相关资源
    最近更新 更多