判断收藏状态页面实现
准备好了后端接口,接下来我们看下如何实现前端页面。
frontend/src/views/MovieDetail.vue
<button
v-on:click="collect_or_cancle(movie.id)"
id="collect"
:class="collectStatus ? 'bg-gray-500' : 'bg-blue-500'"
class="copy text-white w-full px-4 py-1 mt-2 text-sm rounded border"
>
{{ collectMessage }}
</button>
<script>
import axios from "axios";
import Header from "@/components/Header.vue";
import Footer from "@/components/Footer.vue";
export default {
name: "MovieDetail",
data() {
return {
movie: {},
collectStatus: false,
collectMessage: "",
};
},
components: { Header, Footer },
mounted() {
this.get_movie_info();
// 判断一下用户是否登录
if (!this.$store.state.isLogin) {
this.collectStatus = false;
this.collectMessage = "添加收藏";
} else {
const movie_id = this.$route.params.id;
this.get_collect_status(movie_id);
}
},
methods: {
get_movie_info: function () {
axios
.get("/api/movie/" + this.$route.params.id)
.then((response) => (this.movie = response.data));
},
// 获取收藏状态
get_collect_status(movie_id) {
axios
.get("/api/collects/" + movie_id + "/is_collected/", {
headers: {
Authorization: "JWT " + localStorage.getItem("token"),
},
})
.then((response) => {
this.collectStatus = response.data.is_collected;
if (this.collectStatus) {
this.collectMessage = "取消收藏";
} else {
this.collectMessage = "添加收藏";
}
});
},
},
};
</script>
代码解析
这段Vue代码是从一个电影详情页面的组件,它展示了Vue的基础语法和一些进阶用法。下面是对这段代码的主要部分的解析:
Template部分
<button>标签定义了一个按钮,这个按钮用于收藏或取消收藏一个电影。v-on:click="collect_or_cancle(movie.id)"是一个Vue指令,用于监听按钮的点击事件,并调用collect_or_cancle方法,传入当前电影的id作为参数。:class="collectStatus ? 'bg-gray-500' : 'bg-blue-500'"是一个条件类绑定,它根据collectStatus的值动态地切换按钮的背景色。如果collectStatus为真,则应用bg-gray-500类;否则应用bg-blue-500类。class="copy text-white w-full px-4 py-1 mt-2 text-sm rounded border"是静态类绑定,为按钮提供了一系列的样式定义。{{ collectMessage }}是Mustache语法,用于输出collectMessage变量的值到按钮上,显示为“添加收藏”或“取消收藏”。
Script部分
import axios from "axios";表示引入axios库,用于发起HTTP请求。import Header from "@/components/Header.vue";和import Footer from "@/components/Footer.vue";分别引入了页面的头部和尾部组件。export default定义了Vue组件的导出对象。data()函数返回一个对象,定义了组件的数据模型,包括movie(电影信息),collectStatus(收藏状态),collectMessage(按钮文本)。components: { Header, Footer },注册了组件中使用的子组件。mounted()钩子函数在组件挂载完成后执行,用于初始化电影信息和收藏状态。methods对象定义了组件的方法,包括get_movie_info(获取电影信息)和get_collect_status(获取收藏状态)。
动态数据和事件处理
- 通过
axios.get发起HTTP请求来获取电影信息和收藏状态,并更新组件的数据。 - 根据用户是否登录和电影的收藏状态,动态更新按钮的样式和文本。
- 使用
v-on:click监听按钮点击事件,实现收藏或取消收藏的功能。
这段代码展示了Vue.js的核心功能,包括数据绑定、条件渲染、事件处理、组件通信等。通过这些功能,Vue.js能够构建出动态的、交互式的前端应用。
继续阅读完整内容
以上为免费预览。前往「Django + Vue 全栈课程」,查看后续完整讲解、案例演示和配套资料。
查看课程详情