1. 程式人生 > >Django框架(三十)—— 使用Vue搭建前臺

Django框架(三十)—— 使用Vue搭建前臺

目錄

vue的使用

一、建立vue專案

參考另一篇隨筆:https://www.cnblogs.com/linagcheng/p/9883014.html

1.安裝node.js
2.vue腳手架
3.vue create 專案名字

二、pycharm開發vue專案

1、安裝vue.js外掛

setting ---> plugins ---> 左下方install ----> 搜尋vue.js ----> 下載 ---> 重啟

2、執行vue專案

執行按鈕旁邊的editconfigration ---> + ---> npm ---> 右側 Command:run;Script:serve

三、vue專案的目錄結構

assets:靜態資源
components:元件,存放頁面中小的頁面
views:檢視元件,基本存放大型的頁面
APP.vue:根元件
main.js :總的入口js
router.js :路由相關,所有路由的配置,在這裡面
store.js  :vuex狀態管理器

package.json : 專案依賴的檔案

注意:

  • node_modules 專案依賴檔案很多,所有拷貝vue專案時,可以不拷貝,通過npm install參考package.json檔案直接下載專案依賴

  • 將專案傳到Git上,依賴檔案不要傳

  • 每個元件有三部分

    • template

    • style

    • script

四、vue的使用

1、建立新的元件

(1)手動建立一個元件,如index.vue

(2)去路由中配置

import Index from './views/Index.vue'

routes:[
    {
    path: '/index',
    name: 'index',
    component: Index
    },
]

(3)使用元件

<router-link to="/index">index頁面</router-link>

2、顯示資料

<template>
    <div>
        {{ course }}
        <p>
            {{ name }}
        </p>
        <!--for迴圈-->
        <p v-for=" course in courses">
            {{ course }}
        </p>
    </div>
</template>

<script>
    export default {
        data: function () {
            // 返回資料,template可以通過name獲取
            return {
                courses: ['python', 'linux'],
                name: 'tom'
            }
        },
    }
</script>

3、方法的繫結

<template>
    <button @click="test">點我</button>
</template>

<script>
    export default {
        methods: {
            test: function () {
                    this.course=['aaa','ddd','bbb']
            }

        }
    }
    
</script>

五、axios

1、安裝axios

npm install axios

2、使用axios

(1)在mian.js中配置

// 匯入axios
import axios from 'axios'

// 要把axios放到一個全域性變數中
// 把axios賦給了$http這個變數
Vue.prototype.$http = axios

(2)在元件中使用

this.$http.request().then().catch()
this.$http.request({
    url:請求的地址
    method:請求方式
}).then(function(response){
    ....函式回撥處理
})
methods: {
    init: function () {
        //this.$http 就是axios
        // $.ajax({
        //     url:'',
        //     type:'post',
        //     success:function(){}
        // })
        
        let _this=this  // this需要在上面重新賦值給一個變數
        this.$http.request({
            // 在mian.js中配置,_this.$url='http://127.0.0.1:8000/'
            url:_this.$url+'course/',
            method:'get'
        }).then(function (response) {
            //console.log(response)
            //服務端返回的資料
            console.log(response.data)
            _this.course = response.data
        }).catch(function (response) {
            console.log(response)
        })

    },

}