@[TOC]
背景
因为网站的挑战榜模块之前都是前端写的静态数据,适应性不强,我每次加一个标签需要重新发布一次前端,非常麻烦
效果
前端:
django后台动态配置:
接口实现
模型层
类型,标题,json字符串
from django.db import models
from django.utils import timezone
# Create your models here.
class DictModel(models.Model):
kind = models.TextField(blank=True,null=True)
#种类
title=models.CharField(blank=True, null=True, max_length=20)
#标题
describe=models.TextField(blank=True,null=True)
#配置项 json字符串
option=models.TextField(blank=True,null=True)
#发布时间
publish=models.DateTimeField(default=timezone.now)
class Meta:
ordering=("-publish",)
db_table = 'DictModel'
def __str__(self):
return '%s' % (self.title)
视图层
查询接口 get全部,post进行全量匹配
from django.http import JsonResponse
import json
from .models import DictModel
def index(request):#获取所有的文章
try:
if request.method == 'GET':
allDictModel = DictModel.objects.order_by('publish')
resData = []
for dicItem in allDictModel:
resData.append({
"title": dicItem.title,
"option": dicItem.option
})
return JsonResponse({
"code": 200, "data": resData, "msg": 'return all dict'})
elif request.method == 'POST':
print('post')
postData = json.loads(request.body.decode('utf-8'))
print(postData)
kind = postData['kind']
allDictModel = DictModel.objects.order_by('publish')
resData = []
for dicItem in allDictModel:
if str(kind) == str(dicItem.kind):
resData.append({
"title": dicItem.title,
"option": dicItem.option
})
return JsonResponse({
"code": 200, "data": resData, "msg": 'serch dict success'})
return JsonResponse({
"code": 0, "data": [], "msg": 'not allowed'})
except Exception as e:
return JsonResponse({
"code": -1, "data": [], "msg": str(e)})
前端适配
获取接口数据即可
methods定义一个获取接口的方法
getChallengeDict () {
const that = this
that.$axios
.post(that.baseurl + 'dictModel/index/', {
kind: 'challenge'
// 传入索引
})
.then((res) => {
that.challengeConfig = res.data.data.map(item => {
return JSON.parse(item.option)
})
})
.catch((error) => {
throw Error(error)
})
}
渲染层
<ul
v-for="(item, index) in challengeConfig"
:key="index"
class="ul_style"
>
<div
v-bind:class="[
{ li_active: index === activeChallengeIndex },
li_errorClass,
]"
>
<li @click="clickChallengeEvent(item,index)">{
{ item.title }}</li>
</div>
</ul>
我的博客网站链接:https://yongma16.xyz
结束,感谢阅读!