利用django实现搜索功能

前端

– 展示页添加搜索按钮,通过点击事件实现跳转,用来展示搜索出来的内容

<template>
    <div>
      <table border="1">
        <tr>
          <th>分类</th>
        </tr>
        <tr v-for="item in cates">
          <td>{{ item.name }}</td>
        </tr>
      </table>
      <input type="text" v-model="word">
      <button @click="search">搜索</button>
    </div>
</template>

<script>
  import axios from 'axios'
    export default {
        data(){
          return{
            cates:[],
            word:''
          }
        },
      methods:{
          search(){
            console.log(this.word);
             this.$router.push({path:'/search',query:{word:this.word}});
          },
      },
      mounted() {
          axios({
            url:'http://localhost:8000/showcates/',
            method:'get',
          }).then(res=>{
            this.cates = res.data;
          })
      }
    }
</script>

– search页面

<template>
    <div>
      <div v-for="item in datalist">
        {{ item.name }}
      </div>
    </div>
</template>

<script>
  import axios from 'axios'
    export default {
        data(){
          return{
            word:'',
            datalist:[],
          }
        },
      mounted() {
          var word = this.$route.query.word;
          console.log(word);
          axios({
            url:'http://127.0.0.1:8000/showcate/',
            params:{name:word},
            method:'get',
          }).then(res=>{
            console.log(res);
           this.datalist = res.data;
          })
      }
    }
</script>

后端

class ShowCate(APIView):
    def get(self,request):
        name = request.GET.get('name')
        print(name)
        cate = Cate.objects.filter(name__contains=name)
        ser = CateModelSerializer(cate,many=True)
        return Response(ser.data)

你可能感兴趣的:(django+vue)