页面加载的时候直接渲染
不再使用
{{ info.name }}
在发送请求的时候添加属性
delimiters: ['[[', ']]']
,使用[[ info.name ]]
HTML
<dl class="layui-nav-child" id="infos">
<dd data-name="console" v-for="info in infos">
<a :href="'/base/'+ info.id">[[ info.name ]]</a>
</dd>
</dl>
JavaScript
var vm = new Vue({
el: "#info",
delimiters: ['[[', ']]'],
data: {
info: [],
},
mounted: function () {
axios.get('/info/', {
responseType: 'json'
})
.then(response => {
this.info = response.data;
// console.log("下面是后台返回的数据");
// console.log(this.info);
})
.catch(error => {
console.log("获取数据请求失败")
})
},
Vue的双向绑定
- 先使用
v-model=“form_data.class_id"
指定数据来源 - 再使用
v-for="class_ in directions"
遍历数据列表 - 最后使用
v-bind:value="class_.id"
绑定数据(value可换) - 使用
{{ class_.name }}
渲染数据, 注意:上面使用的是[[ ]]
HTML
<!-- Class -->
<label class="layui-form-label">Class</label>
<div class="layui-input-inline">
<select class="layui-input-inline" v-model="form_data.class_id" id="class" lay-verify="required">
<option value="">请选择</option>
<option v-for="class_ in class_s" v-bind:value="class_.id">{{ class_.name }}</option>
</select>
</div>
JavaScript
<!-- 这里是选择位置发送的ajax请求 -->
<script>
var vm = new Vue({
el: "#info",
data: {
info: [],
},
mounted: function () {
axios.get('/info/', {
responseType: 'json'
})
.then(response => {
this.info = response.data;
})
.catch(error => {
// alert(error.response.data);
alert("这里是发送数据的请求")
})
}
})
</script>
页面上有些需要后台返回的数据,使用Vue框架的双向绑定
HTML
<ul class="select" style="width: 100%">
<li class="select-list">
<dl id="select1">
<dt>Info:</dt>
<dd class="select-all selected"><a href="#">不限</a></dd>
<dd v-for="info in infos"><a href="#">{{ info.name }}</a></dd>
</dl>
</li>
</ul>
Javascript
<script>
var vm = new Vue({
el: "#select1",
data: {
infos: [],
},
mounted: function () {
axios.get('/info/100', {
responseType: 'json'
})
.then(response => {
this.infos = response.data[0]["subs"];
})
.catch(error => {
// alert(error.response.data);
alert("这里是发送数据的请求")
})
},
})
</script>
后台
URL
urlpatterns = [
url(r'^info/$', views.InfosModelView.as_view({'get': 'info_key'})),
url(r'^info/(?P<pk>\d+)$', views.InforModelView.as_view({'get': 'info_key'})),
]
序列化器
class InfoSerializer(serializers.ModelSerializer):
class Meta:
model = Info
fields = ["id", "num"]
class InfosSerializer(serializers.ModelSerializer):
subs = InfoSerializer(many=True, read_only=True)
class Meta:
model = Info
fields = ["id", "num", "subs"]
视图函数
class InfosView(ViewSet):
def info(self, request):
info = Info.objects.filter(parent=None)
propulsion_num = InfoSerializer(info, many=True)
return Response(propulsion_num.data)
def num_key(self, request, pk):
propulsion_obj = Info.objects.get(pk=pk)
serializer = InfoSerializer(propulsion_obj)
return Response(serializer.data)
def every_power(self, request):
items = Info.objects.all()
data = []
for i in items:
if i.parent_id:
item = {}
item["id"] = i.id
item["num"] = i.num
data.append(item)
return Response(data)
评论区