django & vue 前后端分离

下载并安装git:  https://www.git-scm.com/download/win
      
      
      
vue开发环境搭建 
下载二进制包   https://nodejs.org/zh-cn/


在cmd中如下显示说明安装成功
C:\Users\EDUTECH> node -v
v14.15.4



新建 ops 目录,在 ops 下面新建 web 目录,作为前端代码目录
(后面会在ops目录下的 devops文件夹是后端代码,和web目录是同级 )

 
进入 web 目录,克隆vue模版
git clone https://github.com/PanJiaChen/vue-admin-template.git


安装node.js(在vue-admin-template目录下操作)
npm install --registry=https://registry.npm.taobao.org 
 
 
注意安装过程中出现war正常,出现error就说明有问题
安装完后,此时它就生成 vue-admin-template\node_modules目录(里边是依赖包),若安装时出错就直接把此目录删除再重新装

关于NPM镜像可参考文档   https://developer.aliyun.com/mirror/NPM?from=tnpm 


运行服务  
D:\ops\web\vue-admin-template> npm run dev


后端代码移动到 ops目录下


安装django cors header ,做此步的话无法通过命令来通过ajax(异步请求)请求数据
pip install django-cors-headers 


文件 settings.py 中增加INSTALLED_APPS
'corsheaders',


 
把所有api的权限取消
在  users\views.py 文件 class UserViewset
#permission_classes = (IsAuthenticated,)

添加中间件监听
文件 settings.py 中 middleware 注意先后顺序,放在 'django.middleware.common.CommonMiddleware' 上 
'corsheaders.middleware.CorsMiddleware',


配置允许跨域的域名
在setting中设置跨域白名单的时候
django-cors-headers包的版本影响报名单写法
版本包小于3.0不用加http
版本包大于3.0则需要加http

这里设成*,允许所有域名跨域请求我数据,如果是线上环境的话,你允许哪个域名请求,这里就写哪个域名即可
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True

CORS_ORIGIN_WHITELIST = (
    'http://127.0.0.1:8000',
)



src\permission.js  
全部注释掉,因为它做了权限验证所以你访问不了

 

文件 settings.py 中,devop后端所有api的权限,这样便于前端获取数据
REST_FRAMEWORK = {
 'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema',
    'PAGE_SIZE':10,
    'DEFAULT_PAGINATION_CLASS':'users.pagination.Pagination',
    'DEFAULT_FILTER_BACKENDS': (
        'django_filters.rest_framework.DjangoFilterBackend',
    ),
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.AllowAny',
        # 'devops.permissions.Permissions',
    ]
}



写接口,新建 src\api\dashboard.js   所有的api接口调用全写在这 
// 请求的模块
import request from '@/utils/request'

// 定义getUserList函数,params参数,
export function getUserList(params) {
  return request({
    // 这个url是跟config/dev.env.js中的BASE_API组合关联的,是url和get拼接在一起的,所以BASE_API中的url后不要加斜线了
    url: 'http://127.0.0.1:8000/users/',
    method: 'get',
    params
  })
}



这是模版中别人写好的,把改成如下自己需要的
src\utils\request.js
import axios from 'axios'
import { Message } from 'element-ui'
// import { getToken } from '@/utils/auth'

// 创建axios实例
const service = axios.create({
  baseURL: process.env.BASE_API, // api的base_url
  timeout: 15000 // 请求超时时间
})

// request拦截器
// service.interceptors.request.use(config => {
//   if (store.getters.token) {
//     config.headers['X-Token'] = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
//   }
//   return config
// }, error => {
//   // Do something with request error
//   console.log(error) // for debug
//   Promise.reject(error)
// })

// respone拦截器
service.interceptors.response.use(
  response => {
  /**
  * code为非20000是抛错 可结合自己业务进行修改
  */
    return response.data
  },
  error => {
    console.log('err' + error)// for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service



给浏览器安装vue插件
在浏览器右上方右键-->扩展程序-->输入vue并安装这个Vue.js devtools



数据展示

(1)找到 https://element.eleme.cn/#/zh-CN/component/table带边框的table表格模版
把el-table代码块全复制到dashboard/index.vue ,根据实际项目,做了修改

<template>
  <div class="dashboard-container">
    <el-table
      :data="tableData"    
      border
      style="width: 100%">  
      <el-table-column
        prop="id"  
        label="id">         
      </el-table-column>
      <el-table-column
        prop="username"
        label="用户名">
      </el-table-column>
      <el-table-column
        prop="email"
        label="email">
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
  // 导入我定义的接口文件dashboard.js中的getUserList函数,@符是指src目录
  import { getUserList } from '@/api/dashboard'
  export default {
    // 定义一变量是在data(){ return{} }中定义
    data() {
      return {
        tableData: []
      }
    },
    created() {
      this.fetchData()
    },
    // methods是把所有方法定义在它中
    methods: {
      fetchData() {
        getUserList().then(res => {
          // tableDate中的内容是我们请求里的result,res就是页面返回的数据
          this.tableData = res.results
        })
      }
    }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.dashboard {
  &-container {
    margin: 30px;
  }
  &-text {
    font-size: 30px;
    line-height: 46px;
  }
}
</style>




添加分页功能 
找到 https://element.eleme.cn/#/zh-CN/component/ 带背景的分页
把代码块拷贝到dashboard/index.vue中的表格el-table下面
<template>
  <div class="dashboard-container">
    <el-table
      :data="tableData"
      border
      style="width: 100%">
      <el-table-column
        prop="id"
        label="id">
      </el-table-column>
      <el-table-column
        prop="username"
        label="用户名">
      </el-table-column>
      <el-table-column
        prop="email"
        label="email">
      </el-table-column>
    </el-table>
    <div style="text-align: center; margin-top: 10px;">
      <el-pagination
        background
        layout="total, prev, pager, next"
        @current-change="handleCurrentChange"
        :total="totalNum">
      </el-pagination>
    </div>
  </div>
</template>

<script>
  // 导入我定义的接口文件dashboard.js中的getUserList函数,@符是指src目录
  import { getUserList } from '@/api/dashboard'
  export default {
    // 1.定义一变量是在data(){ return{} }中定义
    data() {
      return {
        tableData: [],
        totalNum: 0,
        params: {
          page: 1
        }
      }
    },
    created() {
      this.fetchData()
    },
    // 2.methods是把所有方法定义在它中--这里是给变量获取数据
    methods: {
      fetchData() {
        getUserList(this.params).then(res => {
          // tableDate中的内容是我们请求里的result,res就是页面返回的数据
          this.totalNum = res.count
          this.tableData = res.results
        })
      },
      handleCurrentChange(val) {
        this.params.page = val // 给变量page传值
        this.fetchData() // 发起ajax请求
      }
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.dashboard {
  &-container {
    margin: 30px;
  }
  &-text {
    font-size: 30px;
    line-height: 46px;
  }
}
</style>



idc增删改查 
写路由 src/router/index.js
  {
    path: '/idcs',      
    component: Layout,    
    children: [
      {
        path: '',        
        name: 'Idcs',
        component: () => import('@/views/idcs/index'),   
        meta: { title: 'Idcs', icon: 'tree' }
      }
    ]
  },
  
  
  
新建 views/idcs/index.vue
<template>
  <div class="idc">
    <idc-list :value="idcs"></idc-list>             
  </div>
</template>

<script>
  import { getIdcsList } from '@/api/idcs'
  import IdcList from './list'                            

  export default {
    name: 'idc',
    components: {              
      IdcList
    },
    data() {
      return {
        idcs: []
      }
    },
    methods: {
      fetchData() {
        getIdcsList().then(
          res => {
            this.idcs = res.data.results
          }
        )
      }
    },
    created() {
      this.fetchData()
    }
  }
</script>

<style lang='scss' scoped>
  .idc {
    padding: 10px;
  }
</style>



新建 api/idcs.js  
import axios from 'axios'

export function getIdcsList() {
  return axios.get('/api/idcs/')
}

export function createIdc(value) {
  return axios.post('/api/idcs/', value)
}

export function updateIdc(value) {
  return axios.put(`/api/idcs/${value.id}/`, value.params)
}

export function deleteIdc(id) {
  return axios.delete(`/api/idcs/${id}/`)
}



展示组件 views/idc/list.vue
<template>
  <div class="idc-list">
    <el-table
      :data="value"
      style="width: 100%">
      <el-table-column
        label="ID"
        width="180">
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="名称"
        width="180">
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="电话"
        width="180">
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.phone }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="邮箱"
        width="180">
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.email }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="地址"
        width="180">
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.address }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="简称"
        width="180">
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.letter }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="handleEdit(scope.row)">编辑</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
  export default {
    name: 'idc-list',
    props: ['value'],
    methods: {
      handleEdit() {},
      handleDelete() {}
    }
  }
</script>

<style lang='scss'>
  .idc-list {}
</style>



 

posted @ 2021-01-21 15:47  屠魔的少年  阅读(3)  评论(0)    收藏  举报