Vue CLI with the end of the separation project before and after the rapid development of Django

1. The necessary environment, software installation configuration

  1. Installation node.js
  2. Setup Editor pycharm and webstorm
  3. Install Google Chrome
  4. npm change source

npm config set registry https://registry.npm.taobao.org
npm config get registry
npm install -g vue-cli

2. Create a scaffolding, use webstorm open your browser to understand the specific content

  1. Create a scaffold

vue init webpack vueproject
project name, project description, author, etc. 4 Enter
only install vue-router, the other full n
using npm install, y

Running the Project

cd vueproject
npm run dev

3. Routes, to see how the tip is routed

src in the directory structure

  1. assets: static file
  2. component: put the component
  3. router: Routing
  4. App.ve: page entry file
  5. main.js: program entry file, load a variety of common components

Create a route

  1. Create a new component User.vue

    <template>
    	<div id="user">
    		{ { page_info } }
    	</div>
    </template>
    <script>
    	export default {
    		name: "User",
    		data(){
    			return {
    				page_info: "this User page"
    			}
    		}
    	}
    </script>
    <style scoped>
    </style>
    
  2. User configuration routing router / index.js in

    import Vue from 'vue'
    import Router from 'vue-router'
    import HelloWorld from '@/components/HelloWorld'
    import User from '@/components/User'
    
    Vue.use(Router)
    
    export default new Router({
      routes: [
        {
          path: '/',
          name: 'HelloWorld',
          component: HelloWorld
        },
        {
          path: '/user',
          name: 'User',
          component: User,
        }
      ]
    })
    
  3. Application routing App.vue in /and/user

    <template>
      <div id="app">
        <img src="./assets/logo.png"><br />
        <router-link to="/">Root</router-link>
        <router-link to="/user">User</router-link>
        <hr />
        <router-view/>
      </div>
    </template>
    
    <script>
    export default {
      name: 'App'
    }
    </script>
    
    <style>
    #app {
      font-family: 'Avenir', Helvetica, Arial, sans-serif;
      -webkit-font-smoothing: antialiased;
      -moz-osx-font-smoothing: grayscale;
      text-align: center;
      color: #2c3e50;
      margin-top: 60px;
    }
    </style>
    

4. Preparation before sending a request, set up the operating environment django

Create a django project

  1. Create a django project webproject, application mysite directly pycharm
  2. Initialize the databasepython manage.py migrate

Modify settings.py

  1. Allow access to all hostsALLOWED_HOSTS = ['*']
  2. Commented'django.middleware.csrf.CsrfViewMiddleware',
  3. Language into ChineseLANGUAGE_CODE = 'zh-Hans'
  4. Time zone changed to ShanghaiTIME_ZONE = 'Asia/Shanghai'
  5. USE_TZ = False
  6. Running the Projectpython manage.py runserver
  7. Static files instead of separating the front and rear endSTATIC_URL = '/api/static/'

URL routing configuration

  1. The total route

    from django.contrib import admin
    from django.urls import path, include
    
    urlpatterns = [
    	path('admin/', admin.site.urls),
    	path('api/', include("mysite.urls"))
    ]
    
  2. Sub-routing

    from django.urls import path
    from mysite import views
    
    urlpatterns = [
    	path("test/", views.test)
    ]
    
  3. View function

    from django.http import JsonResponse
    
    def test(request):
    	return JsonResponse({"status": 0, "message": "this is message"})
    
  4. Access in the browserhttp://127.0.0.1:8000/api/test/

5. On django axios cross-domain request using proxy data django

  1. Installation axiosnpm install axios --save

  2. Sign in axios in main.js

    import Vue from 'vue'
    import App from './App'
    import router from './router'
    import axios from 'axios'
    
    Vue.use(axios);
    Vue.config.productionTip = false
    Vue.prototype.$axios = axios
    
    /* eslint-disable no-new */
    new Vue({
      el: '#app',
      router,
      components: { App },
      template: '<App/>'
    })
    
  3. Receiving a data transmission over the rear end of the User.vue

    <template>
    	<div id="user">
    		{ { page_info } }
    	</div>
    </template>
    <script>
    	export default {
    		name: "User",
    		data(){
    			return {
    				page_info: "this User page"
    			}
    		},
        created() {
          this.$axios.get("/api/test/")
            .then(response => {
              console.log(response.data)
            })
        }
    	}
    </script>
    <style scoped>
    </style>
    
  4. To solve cross-domain issue, modify the config / index.js

    proxyTable: {
      '/api': {
        target: 'http://127.0.0.1:8000/api/', //接口域名
        changeOrigin: true, //是否跨域
        pathRewrite: {
          '^/api':'' ,//需要rewrite重写的
        }
      }
    },
    
  5. Visit http: // localhost: 8080 / # / user will be able to receive data, but can not be displayed

6. fetch data from the database table to render vue

  1. Modify User.vue pass over the back-end data displayed

    <template>
    	<div id="user">
    		{ { page_info } }
        <br />
        { { django_message } }
    	</div>
    </template>
    <script>
    	export default {
    		name: "User",
    		data(){
    			return {
    				page_info: "this User page",
            django_message: ""
    			}
    		},
        created() {
          this.$axios.get("/api/test/")
            .then(response => {
              this.django_message = response.data.message
            })
        }
    	}
    </script>
    <style scoped>
    </style>
    
  2. Stu create the table in models.py

    from django.db import models
    
    # Create your models here.
    class Stu(models.Model):
    	id = models.IntegerField(primary_key=True,auto_created=True)
    	name = models.CharField(max_length=200)
    
  3. Generated migration filepython manage.py makemigrations

  4. Perform the migration filepython manage.py migrate

  5. Stu registration table in the models.py

    from django.contrib import admin
    from . import models
    
    # Register your models here.
    admin.site.register(models.Stu)
    
  6. Create a super administrator python manage.py createsuperuser, user name caoyang, passwordMm23456

  7. Run the project, visit127.0.0.1:8000/admin/login

  8. Add a few users to student table

  9. Returns the data table views.py

    from django.http import JsonResponse
    from .models import Stu
    
    # Create your views here.
    def test(request):
    	return JsonResponse({"status": 0, "message": "this is django_message"})
    
    def ret_user(request):
    	if request.method == "GET":
    		db = Stu.objects.all()
    		db = [i.name for i in db]
    		return JsonResponse({"status":0,"data":db})
    	else:
    		return JsonResponse({"status":1,"message":"you need GET method"})
    
  10. Configuration sub-routepath("user/",views.ret_user)

  11. Access http://127.0.0.1:8000/api/user/will be able to return the data

  12. Modify front-end interface User.vue

    <template>
    	<div id="user">
    		{ { page_info } }
        <br />
        { { django_message } }
        <br />
        <table>
          <tr>
            <th>user</th>
          </tr>
          <tr v-for="user in user_list" :key='user'>
            <td>{ { user } }</td>
          </tr>
        </table>
    	</div>
    </template>
    <script>
    	export default {
    		name: "User",
    		data(){
    			return {
    				page_info: "this User page",
            django_message: "",
            user_list: [],
    			}
    		},
        created() {
          this.$axios.get("/api/test/")
            .then(response => {
              this.django_message = response.data.message
            });
          this.$axios.get("/api/user/")
            .then(response => {
              this.user_list = response.data.data
            })
        }
    	}
    </script>
    <style scoped>
    </style>
    
  13. Access http://localhost:8080/#/userto the data received

7. django json serialized data to facilitate identification vue

  1. Import views.py the from django.core import serializersserialization module, queryset can be converted into json

  2. Modify ret_user view function, visithttp://127.0.0.1:8000/api/user/

    def ret_user(request):
    	if request.method == "GET":
    		json = serializers.serialize("json",Stu.objects.all())
    		return JsonResponse({"status":0,"data":json})
    	else:
    		return JsonResponse({"status":1,"message":"you need GET method"})
    
  3. Modify front-end interface User.vue, visithttp://localhost:8080/#/user

    <template>
    	<div id="user">
    		{ { page_info } }
        <br />
        { { django_message } }
        <br />
        <table>
          <tr>
            <th>id</th>
            <th>user</th>
          </tr>
          <tr v-for="user in user_list" :key='user'>
            <td>{ { user.pk } }</td>
            <td>{ { user.fields.name } }</td>
          </tr>
        </table>
    	</div>
    </template>
    <script>
    	export default {
    		name: "User",
    		data(){
    			return {
    				page_info: "this User page",
            django_message: "",
            user_list: [],
    			}
    		},
        created() {
          this.$axios.get("/api/test/")
            .then(response => {
              this.django_message = response.data.message
            });
          this.$axios.get("/api/user/")
            .then(response => {
              this.user_list = JSON.parse(response.data.data)
            })
        }
    	}
    </script>
    <style scoped>
    </style>
    
    
Published 13 original articles · won praise 12 · views 1353

Guess you like

Origin blog.csdn.net/weixin_45158297/article/details/104299960