我正在使用Vue 3.6.3构建电影列表页面。主页显示电影列表,仅包含每部电影的简要信息,用户可以单击每部电影标题的标题以进入包含有关电影详细信息的页面。我使用vue-router来帮助我进行过渡。
根组件是App.vue,实际上除了显示其子组件外什么都不做。
App.vue中的重要代码:
<template>
<div id="app">
<router-view></router-view>
</div>
</template>
路由器安装在App.vue上,我创建了routers.js文件来定义路由,然后在main.js中创建路由器。
来自routers.js的代码:
import App from './App.vue'
import FilmList from './components/FilmList.vue'
import DetailPage from './components/DetailPage.vue'
const routers = [{
path: '/',
redirect: '/filmlist',
component: App,
children: [{
path: '/filmlist',
name: 'filmlist',
component: FilmList
},
{
path: '/detail/:id',
name: 'detail',
component: DetailPage
}
]
}]
export default routers
来自main.js的代码:
import Vue from 'vue'
import VueRouter from 'vue-router'
import App from './App.vue'
import routes from './routers'
Vue.use(VueRouter)
Vue.config.productionTip = false
const router = new VueRouter({
mode: 'history',
routes: routes
})
new Vue({
router: router,
render: h => h(App),
}).$mount('#app')
App.vue组件具有两个子项,即FilmList和DetailPage。首先,将显示FilmList,在用户单击其中的一个之后,它将根据路由器中的 id 参数跳转到特定电影的详细信息页面。收到 id 参数后,DetailPage.vue应该从电影列表中选择一部电影并显示其详细内容。
来自FilmList.vue的代码:
<template>
<div id="filmlist">
<film-brief
v-for="(film, index) in filmList[pageIndex-1]"
v-bind:key="film._id"
v-bind:index="index + groupCount*(pageIndex-1)"
v-bind:film="film"
></film-brief>
<div class="buttons">
<jump-button
class="button"
v-for="index in buttonIndexList"
:key="index.id"
v-bind:index="index"
v-on:jump-page="pageIndex = index.id"
></jump-button>
</div>
</div>
</template>
<script>
import FilmBrief from "../components/FilmBrief.vue";
import films from "../assets/films.json";
import JumpButton from "../components/JumpButton.vue";
const GroupCount = 10;
export default {
name: "FilmList",
data: function() {
return {
films,
pageIndex: 1,
pageCount: Math.ceil(films.length / GroupCount),
groupCount: GroupCount
};
},
components: {
FilmBrief,
JumpButton
},
......
来自FilmBrief.vue的代码:
<template>
<div class="film-brief">
<div class="poster">
<img :src="imgSrc">
</div>
<div class="info">
<router-link
:to="{
name: 'detail',
params: {
id: index
}
}"
>
<div class="heading" v-html="title"></div>
</router-link>
<div class="ratings">{{film.rating.average}}</div>
<div class="ontime">{{pubdate}}</div>
<div class="type">{{genres}}</div>
</div>
</div>
</template>
<script>
import errorImg from "../assets/imgErr.jpg";
export default {
name: "FilmBrief",
props: ["film", "index"],
data: function() {
return {
imgSrc: "",
imgErrSrc: errorImg
};
},
methods: {
loadImg(resolve, reject) {
let originImgSrc = this.film.poster;
let img = new Image();
img.src = originImgSrc;
img.onload = function() {
resolve({
src: img.src
});
};
img.onerror = function(e) {
reject(e);
};
}
},
created: function() {
this.loadImg(
response => {
this.imgSrc = response.src;
},
reject => {
console.log("图片加载失败");
this.imgSrc = this.imgErrSrc;
}
);
},
......
DetailPage.vue中的代码:
<template>
<div class="detail-page">
<div class="poster">
<img :src="this.imgSrc">
</div>
<div class="details">
<ul>
<li id="title" v-html="title"></li>
<li id="director">{{directors}}</li>
<li id="writers">{{writers}}</li>
<li id="casts">{{casts}}</li>
<li id="genres">{{genres}}</li>
<li id="duration">{{duration}}</li>
<li id="pubdate">{{pubdate}}</li>
<li id="summary"></li>
</ul>
</div>
</div>
</template>
<script>
import errorImg from "../assets/imgErr.jpg";
import films from "../assets/films.json";
export default {
name: "DetailPage",
props: [],
data: function() {
return {
id_: this.$route.params.id,
film: films[id_],
imgSrc: "",
imgErrSrc: errorImg,
duration: "片长:" + this.film.duration + "分钟",
summary: "简介:" + this.film.summary
};
},
methods: {
loadImg(resolve, reject) {
let originImgSrc = this.film.poster;
let img = new Image();
img.src = originImgSrc;
img.onload = function() {
resolve({
src: img.src
});
};
img.onerror = function(e) {
reject(e);
};
},
getList(name, list) {
let result = "";
result += name;
for (let i = 0; i < list.length; i++) {
result += list[i].name;
if (i !== list.length - 1) {
result += " / ";
}
}
return result;
}
},
created: function() {
this.loadImg(
response => {
this.imgSrc = response.src;
},
reject => {
console.log("图片加载失败");
this.imgSrc = this.imgErrSrc;
}
);
},
computed: {
title: function() {
let originalTitle = "";
originalTitle += this.film.title;
let index = originalTitle.indexOf(" ");
let input = originalTitle[index - 1];
let isPunc =
(input >= "A" && input <= "Z") || (input >= "a" && input <= "z");
if (!isPunc) {
return (
originalTitle.slice(0, index) +
"<br>" +
originalTitle.slice(index + 1)
);
} else {
return originalTitle;
}
},
directors: function() {
return this.getList("导演:", this.film.directors);
},
writers: function() {
return this.getList("编剧:", this.film.writers);
},
casts: function() {
return this.getList("主演:", this.film.casts);
},
genres: function() {
let genres = this.film.genres;
let str = "";
for (let i = 0; i < genres.length; i++) {
str += genres[i];
if (i !== genres.length - 1) {
str += " / ";
}
}
return str;
},
pubdate: function() {
let dates = this.film.pubdate;
if (dates[0] === "") {
return "上映时间未知";
} else {
return "上映时间:" + dates[0];
}
}
}
};
</script>
单击后,浏览器中显示的路由是确定的,例如“ http://localhost:8080/detail/11”,但是该页面未显示任何内容,并且控制台中的错误如下:
[Vue warn]: Error in data(): "ReferenceError: id_ is not defined"
found in
---> <DetailPage> at src/components/DetailPage.vue
<App> at src/App.vue... (1 recursive calls)
ReferenceError: id_ is not defined
at VueComponent.data (DetailPage.vue?b507:31)
at getData (vue.runtime.esm.js?2b0e:4742)
at initData (vue.runtime.esm.js?2b0e:4699)
at initState (vue.runtime.esm.js?2b0e:4636)
at VueComponent.Vue._init (vue.runtime.esm.js?2b0e:5000)
at new VueComponent (vue.runtime.esm.js?2b0e:5148)
at createComponentInstanceForVnode (vue.runtime.esm.js?2b0e:3283)
at init (vue.runtime.esm.js?2b0e:3114)
at merged (vue.runtime.esm.js?2b0e:3301)
at createComponent (vue.runtime.esm.js?2b0e:5972)
[Vue warn]: Error in created hook: "TypeError: Cannot read property 'poster' of undefined"
found in
---> <DetailPage> at src/components/DetailPage.vue
<App> at src/App.vue... (1 recursive calls)
<Root>
以及类似的许多其他警告。
稍后,我认为也许是因为 id 参数应该在其他属性访问之前加载,因此我将其添加到DetailPage.vue中的创建的中。 :
`created: function() {
this.film = films[this.$route.params.id];
this.loadImg(
response => {
this.imgSrc = response.src;
},
reject => {
console.log("图片加载失败");
this.imgSrc = this.imgErrSrc;
}
);
},
现在可以加载一些信息,但不能加载其他一些信息,例如海报和持续时间。警告包括:
vue.runtime.esm.js?2b0e:619 [Vue warn]: Error in data(): "TypeError: Cannot read property 'duration' of undefined"
found in
---> <DetailPage> at src/components/DetailPage.vue
<App> at src/App.vue... (1 recursive calls)
<Root>
TypeError: Cannot read property 'duration' of undefined
at VueComponent.data (DetailPage.vue?b507:34)
at getData (vue.runtime.esm.js?2b0e:4742)
at initData (vue.runtime.esm.js?2b0e:4699)
at initState (vue.runtime.esm.js?2b0e:4636)
at VueComponent.Vue._init (vue.runtime.esm.js?2b0e:5000)
at new VueComponent (vue.runtime.esm.js?2b0e:5148)
at createComponentInstanceForVnode (vue.runtime.esm.js?2b0e:3283)
at init (vue.runtime.esm.js?2b0e:3114)
at merged (vue.runtime.esm.js?2b0e:3301)
at createComponent (vue.runtime.esm.js?2b0e:5972)
那么,为什么?如何显示所有信息?
如果我的英语不好为您带来麻烦,请多谢!
答案 0 :(得分:0)
您的问题是由data()
组件中的DetailPage
函数引起的。
data: function() {
return {
id_: this.$route.params.id,
film: films[id_],
imgSrc: "",
imgErrSrc: errorImg,
duration: "片长:" + this.film.duration + "分钟",
summary: "简介:" + this.film.summary
};
},
有几个问题:
film: films[id_]
无法正常工作-id_
的任何地方都未定义,因此film
道具也将未定义。
duration: "片长:" + this.film.duration + "分钟"
-您无法使用data
访问其他this
道具。
您应该使您的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: ""
};
},
然后在您的created
或mounted
钩中加载它:
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;
}
);
},