[Vuejs]-How to render contents based on the params received from vue-router?

0👍

Your problem is caused by your data() function in your DetailPage component.

  data: function() {
    return {
      id_: this.$route.params.id,
      film: films[id_],
      imgSrc: "",
      imgErrSrc: errorImg,
      duration: "片长:" + this.film.duration + "分钟",
      summary: "简介:" + this.film.summary
    };
  },

There are several issues:

film: films[id_] won’t work – id_ is not defined anywhere so film prop will be undefined as well.

duration: "片长:" + this.film.duration + "分钟" – you can’t access other data props using this.

You should make your data() function contain default/empty/placeholder data:

  data: function() {
    return {
      id_: this.$route.params.id, // this is fine - you can access $route because it's global
      film: {}, // empty object or some object type containing placeholder props
      imgSrc: "",
      imgErrSrc: errorImg,
      duration: "",
      summary: ""
    };
  },

Then in your created or mounted hook, load it:

  created: function() {
    this.film = films[this.$route.params.id];
    this.duration = "片长:" + this.film.duration + "分钟";
    this.summary = "简介:" + this.film.summary;
    this.loadImg(
      response => {
        this.imgSrc = response.src;
      },
      reject => {
        console.log("图片加载失败");
        this.imgSrc = this.imgErrSrc;
      }
    );
  },

Leave a comment