您当前的位置:首页 > 计算机 > 软件应用 > 开发(IDE)

Vue配合Django使用

时间:03-29来源:作者:点击数:

Vue

Vue.js是前端三大新框架:Angular.js、React.js、Vue.js之一,Vue.js目前的使用和关注程度在三大框架中稍微胜出,并且它的热度还在递增。

Vue.js读音 /vjuː/, 类似于 view

Vue.js是一个轻巧、高性能、可组件化的MVVM库,同时拥有非常容易上手的API

Vue.js是一个构建数据驱动的Web界面的库

Vue.js是一套构建用户界面的 渐进式框架

通俗的说:

  • Vue.js是一个构建数据驱动的 web 界面的渐进式框架
  • Vue.js 的目标是通过尽可能简单的 API 实现响应的数据绑定和组合的视图组件
  • 核心是一个响应的数据绑定系统

Vue作者

尤雨溪是Vue.js框架的作者,他认为,未来App的趋势是轻量化和细化,能解决问题的应用就是好应用。而在移动互联网时代大的背景下,个人开发者的机遇在门槛低,成本低,跨设备和多平台四个方面。

第一个Vue

官方提供了两个包
  • 开发环境版本
  • 生产环境版本

data

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
        <!-- 开发环境版本,包含了有帮助的命令行警告 -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
    <div id="app">
        <a href="#">{{ message }}</a>
        <span>{{ hello }}</span>
        <hr>
        <span>{{ word }}</span>
    </div>

</body>
<script type="text/javascript">
    var vm = new Vue({
        el:"#app",
        data:{
            message:"领取优惠卷",
            hello:"hi en heng",
            word:'你好!'

        }
    })


</script>
</html>

v-bind

<span v-bind:title="show">鼠标放在这里</span>
简写:
<span :title="show">鼠标放在这里</span>

var vm = new Vue({
        el:"#app",
        data:{
            show:'当前时间是:'+ new Date().toLocaleString()
        }
    })

v-if



<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!--    导入vue-->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<!--定义一个标签给id -->
    <div id="app">
        <span>{{ message }}</span>
        <hr>
        <a href="#" v-if="isLogin">欢迎你回来!</a>
        <hr>
        <a href="#" v-if="level === 1 ">青铜</a>
        <a href="#" v-else-if="level === 2 ">白银</a>
        <a href="#" v-else>王者</a>
        <hr>
        <span v-if="seen">v-if</span><br>
        <span v-show="seen">v-show</span>


    </div>
</body>
<!--创建vue实例-->
<script type="text/javascript">
    var vm = new Vue({
        el:'#app',
        data:{
            message:'hello',
            is_Login:false,
            level:2,
            seen:false
        }


    })



</script>
</html>

v-show用法和v-if大致一样,但是它不支持v-else,它和v-if的区别是,它制作元素样式的显示和隐藏,元素一直是存在的

v-for

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!--    导入vue-->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<!--定义一个标签给id -->
    <div id="app">
        <span>{{ message }}</span>

        <hr>
        <ul>
            <li v-for=" (item,index) in items">{{ index+1 }}----{{ item }}</li>
        </ul>
        <hr>
        <!--对对象遍历-->
        <ul>
            <li v-for="(value,key) in object ">{{ key }}----{{ value }}</li>

        </ul>
        <hr>
        <ul>
            <li v-for="todo in todos">{{ todo.title}}---{{ todo.author}}</li>

        </ul>


    </div>
</body>
<!--创建vue实例-->
<script type="text/javascript">
    var vm = new Vue({
        el:'#app',
        data:{
            message:'hello',
            items:['python','mysql','linux','html','js','css'],
            object: {
      title: 'How to do lists in Vue',
      author: 'Jane Doe',
      publishedAt: '2016-04-10'
    },
            todos: [
       {
        title: 'Vue',
        author: 'Jane Doe',
        publishedAt: '2016-04-10'
      },
      {
        title: 'python',
        author: 'Ricky',
        publishedAt: '2019-04-10'
      },
      {
        title: 'itcast',
        author: 'itcast',
        publishedAt: '2006-05-08'
      }
    ]
        }

    })


</script>
</html>

methods

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!--    导入vue-->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<!--定义一个标签给id -->
    <div id="app">
        <span>{{ message }}</span>
        <button v-on:click="login">登陆</button>
        <br>
        <a href="javascript:;" @click="regsiter">注册</a>
        <hr>
        <button @click="add(counter)">点击+1</button>

    </div>
</body>
<!--创建vue实例-->
<script type="text/javascript">
    var vm = new Vue({
        //接管标签
        el:'#app',
        //绑定数据
        data: {
            message: 'hello',
            counter:1,
            total:0,
        },
        //方法
        methods:{
            login:function (){
                alert('我被点击了')


            },
            regsiter:function (){
                alert('注册')
            },
            add:function(counter){
                //this表示当前的vue,我们通过this.total来获取data中的变量
                this.total+= counter
                alert(this.total)

            }
        }

    })



</script>
</html>

v-on 绑定事件

简写@

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!--    导入vue-->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<!--定义一个标签给id -->
    <div id="app">
        <span>{{ message }}</span>
        <button v-on:click="login">登陆</button>
        <br>
        <a href="javascript:;" @click="regsiter">注册</a>
        <hr>
        <button @click="add(counter)">点击+1</button>

    </div>
</body>
<!--创建vue实例-->
<script type="text/javascript">
    var vm = new Vue({
        //接管标签
        el:'#app',
        //绑定数据
        data: {
            message: 'hello',
            counter:1,
            total:0,
        },
        //方法
        methods:{
            login:function (){
                alert('我被点击了')


            },
            regsiter:function (){
                alert('注册')
            },
            add:function(counter){
                //this表示当前的vue,我们通过this.total来获取data中的变量
                this.total+= counter
                alert(this.total)

            }
        }

    })



</script>
</html>

v-model

双向绑定

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!--    导入vue-->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<!--定义一个标签给id -->
<div id="app">
    <span>{{ message }}</span>
    <hr>
    <table>
        <tr>
            <td>用户名</td>
            <td><input type="text" name="username" v-model="username"></td>

        </tr>
        <tr>
            <td>密码</td>
            <td><input type="password" name="password1" v-model="password1"></td>

        </tr>
        <tr>
            <td>确认密码</td>
            <td><input type="password" name="password2" v-model="password2"></td>

        </tr>
        <tr>
            <td>性别</td>
            <td><input type="radio" name="sex" value="boy" v-model="sex">男
                <input type="radio" name="sex" value="girl" v-model="sex">女</td>
        </tr>
        <tr><td>爱好</td>
        <td>
          足球 <input type="checkbox" name="like" value="足球" v-model="like">
          篮球 <input type="checkbox" name="like" value="篮球" v-model="like">
          兵乓球<input type="checkbox" name="like" value="兵乓球" v-model="like">
        </td>
      </tr>

    </table>
    <button v-on:click="register">注册</button>

</div>
</body>
<!--创建vue实例-->
<script type="text/javascript">
    var vm = new Vue({
        //接管标签
        el: '#app',
        //绑定数据
        data: {
            message: 'hello',
            username:'',
            password1:'',
            password2:'',
            sex:'',
            like:[]


        },
        methods:{
            register:function(){
                alert(this.username+this.password1+this.password2+this.sex+this.like)
            }
        }
    })


</script>
</html>

todolist 案例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!--    导入vue-->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>

<!--定义标签-->
<div id="app">
<span>{{ message }}</span>
<input type="text" name="todoitem" v-model="newitems">
<button @click="add">添加</button>
<hr>
<ul>
    <li v-for="(item,index) in items">
        <a href="javascript:;" @click="up(index)">↑</a>
        {{ item}}
        <a href="javascript:;" @click="deleteitem(index)">删除</a>
        <a href="javascript:;" @click="down(index)">↓</a>

    </li>

</ul>

</div>


</body>
<!--创建vue实例-->
<script type="text/javascript">
    var vm = new Vue({
        //接管标签
        el: '#app',
        //绑定数据
        data: {
            message: 'hello',
            items:['学习html','学习Django','学习MySQL'],
            newitems:''



        },
        //绑定事件
        methods:{
            add:function (){
                this.items.push(this.newitems),
                    this.newitems=''
            },
            deleteitem:function(index){
                this.items.splice(index,1);
            },
            up:function(index){
            //    获取当前元素
                current = this.items[index]
            //    先把当前元素删除
                this.items.splice(index,1)
            //    在添加,添加的时候索引-1
                this.items.splice(index-1,0,current)
            },
            down:function(index){
                 //    获取当前元素
                current = this.items[index]
            //    先把当前元素删除
                this.items.splice(index,1)
            //    在添加,添加的时候索引-1
                this.items.splice(index+1,0,current)
            }
        }
    })


</script>
</html>

es6语法

let只能在里边用

var 可以在外面用

const:const声明一个只读的常量。一旦声明,常量的值就不能改变。

es5的对象

var person = { 
    name:'itcast',
    age:13,
    say:function(){
        alert('hello')
    }
}

person.say()

es6的对象

//定义变量
var name='itcast';
var age=13;
//创建对象
var person = {
    name,
    age,
    say:function(){
        alert('hello');
    }
};
//调用
person.say()

箭头函数

作用:

  • 定义函数新的方式
  • 改变this的指向

定义函数新的方式

//无参数,无返回值
var say = ()=> {
    alert('我是无参数无返回值函数');
}
//有参数,无返回值
var eat = food => {
    alert('我喜欢吃'+food);
}
//有参数,有返回值
var total = (num1,num2) => {
    return num1+num2;
}

改变this的指向

如果层级比较深的时候, this的指向就变成了window, 这时候就可以通过箭头函数解决这个指向的问题

var person = {
    name:'itcast',
    age:13,
    say:function(){
        alert('my name is ' + this.name);
    }
}
//调用
person.say()

生命周期

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!-- 开发环境版本,包含了有帮助的命令行警告 -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
    <div id="app">
  {{ message }}
    </div>
</body>
<script>
    var vm = new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue!'
  },
        //生命周期的钩子(函数)没有在methods
        beforeCreate:function(){
      console.log('beforeCreate')
        },
        created:function(){
      console.log('created')
        },
        beforeMount:function(){
      console.log('beforeMount')
        },
        mounted:function(){
      console.log('mounted')
        },
        beforeDestroy:function(){
      console.log('beforeDestroy')
        },
        destroyed:function(){
      console.log('destroyed')
        }
})


</script>
</html>

axios发送ajax

vue的大胡子语法和django和flask模板语法冲突

delimiters:['[[',']]']
我们使用Vue的js发送get和post请求,请求我们用django框架进行解析返回渲染页面
首先我们创建一个django项目,创建一个app,注册使用,配置url,书写view,书写Vue
这里就不展示太多了,

View代码如下:

import json

from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View


class LoginView(View):
    def get(self, request):
        return render(request, 'login.html')

    def post(self, request):
        pass


class ReceView(View):
    def get(self, request):
        data = request.GET
        username = data.get('username')
        password = data.get('password')
        return JsonResponse({'info':{'username':username,'password':password}})

    def post(self, request):
        data = json.loads(request.body.decode())
        username = data.get('username')
        password = data.get('password')
        return JsonResponse({'info': {'username': username, 'password': password}})


URL配置

from django.conf.urls import url
from book.views import *

urlpatterns = [
    url(r'^login/',LoginView.as_view()),
    url(r'^rece/',ReceView.as_view()),
]

Vue代码:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
    <!-- 开发环境版本 -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
        <!-- 导入axios -->
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="app">


[[ message ]]
    <hr>

    [[ username ]]
    <button @click="login">登录</button>
    <button @click="login1">post</button>


</div>
</body>
<script type="text/javascript">
    var vm = new Vue({
        el:'#app',
        delimiters:["[[","]]"],
        data:{
            message:'hello Vue!',
            username:''
        },
        methods:{
            login:function(){
                var url = 'http://127.0.0.1:8000/rece/?username=itcast&password=123'
                axios.get(url).then((response)=>{
                    console.log(response.data.info.username)
                    this.username = response.data.info.username

                }).catch((error)=>{

                    console.log(error)
                })

            },
            login1:function(){
                var url = 'http://127.0.0.1:8000/rece/'
                axios.post(url,{"username":'itheima','password':'123'})
                .then((response)=>{
                 console.log(response.data.info.username)
                    this.username = response.data.info.username
                }).catch((error)=>{
                    console.log(error)
                })
            }
        }

    })

</script>
</html>

get效果:

在这里插入图片描述

post效果:

在这里插入图片描述
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门