七十、Vue-CLI项目搭建

一、环境搭建

1、安装服务器node

官网下载 https://nodejs.org/zh-cn/
node:用C++语言编写,用来运行JavaScript语言
    node可以为前端项目提供server (包含了socket)

2、安装包管理器npm

管理员命令行安装:window系统:npm install -g cnpm --registry=https://registry.npm.taobao.org
          Mac系统: sudo npm install -g cnpm --registry=https://registry.npm.taobao.org

索引npm的指令都可以换成cnpm
  npm install vuex => cnpm install vuex

3、安装脚手架:

命令行安装:cnpm install -g @vue/cli
如果报错:npm cache clean --force

二、创建Vue项目

1、cd 到目标目录

2、创建项目:vue create 目录名

注意:要提前进入目标目录(项目应该创建在哪个目录下)
   选择自定义方式创建项目,选取Router, Vuex插件

 

3、启动项目

①终端启动

进入项目:cd到项目目录
启动项目:npm run serve

②pycharm配置

在App.vue中安装vue.js插件,如果没有提示,在settings里的plugins里搜Vue.js安装,然后重启
配置项目的npm启动项:
直接拷贝,依赖需要自己安装cpm install

三、项目目录

四、组件

1、在根组件中渲染页面组件

①Main.vue 主页组件

<template>
    <div class="main">
        <h1>{{ title }}</h1>
    </div>
</template>

<script>
    export default {
        name: "Main",
        data: function () {
            return {
                title: '主页'
            }
        }
    }
</script>

<style scoped>
    .main {
        height: 100vh;
        background-color: orange;
    }
    h1 {
        margin: 0;
        color: red;
    }
</style>    

②App.vue根组件

<template>
    <div id="app">
        <!-- 3.使用 -->
        <Main></Main>
    </div>
</template>
<script>
    // 1.导入
    import Main from '@/views/Main'
    export default {
        // 2.注册
        components: {
            Main: Main
        }
    }
</script>
<style>
    html, body {
        margin: 0;
    }
</style>

五、路由router.js

1、在根组件中设计转跳页面的导航栏

<template>
    <div id="app">
        <ul class="nav">
            <li>主页</li>
            <li>商品页</li>
            <li>个人页</li>
        </ul>
        
    </div>
</template>

<script>
    import Main from '@/views/Main'

    export default {
        components: {
            Main: Main
        }
    }
</script>

<style>
    .nav {
        height: 200px;
        background-color: orange;
    }
    .nav li{
        float: left;
        height: 200px;
        width: 200px;
        text-align: center;   /* 水平居中 */
        line-height: 200px;    /* 垂直居中 */
    }
    .nav li:hover {
        background-color: aqua;
    }

    html, body, ul {
        margin: 0;
    }
    ul {
        list-style: none;
    }
</style>
View Code

2、创建三个页面

主页   Main
商品页 Goods
个人页 User

3、组件配置

import Vue from 'vue'
import Router from 'vue-router'
import Main from './views/Main.vue'
import Goods from './views/Goods.vue'
import User from './views/User.vue'
// import Home from './views/Home.vue'

Vue.use(Router)

export default new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  routes: [
    {
      path: '/',
      name: 'main',
      component: Main
    },
    {
      path: '/goods',
      name: 'goods',
      component: Goods
    },
    {
      path: '/user',
      name: 'user',
      component: User
    },
  ]
})
router.js
<template>
    <div id="app">
        <ul class="nav">
            <!--<router-link>组件支持用户在具有路由功能的应用中点击导航。
            通过to属性指定目标地址,默认渲染为带有正确连接的<a>标签-->
            <li><router-link to="/">主页</router-link></li>
            <li><router-link to="/goods">商品页</router-link></li>
            <li><router-link to="/user">个人页</router-link></li>
        </ul>
        <!--不想跳转到新页面,只在当前页面切换着显示,那么就要涉及到路由的嵌套。
        点击每个导航链接会跳转到不同的组件,并且加上<router-view></router-view>这个标签-->
        <router-view/>

    </div>
</template>

<script>
    import Main from '@/views/Main'

    export default {
        components: {
            Main: Main
        }
    }
</script>

<style>
    .nav {
        height: 200px;
        background-color: red;
    }
    .nav li{
        float: left;
        height: 200px;
        width: 400px;
        text-align: center;   /* 水平居中 */
        line-height: 200px;    /* 垂直居中 */
    }
    .nav li:hover {
        background-color: aqua;
    }
    .nav li a {
        text-decoration: none;
        font: bold 30px/30px 'STSong';
    }

    html, body, ul, h1 {
        margin: 0;
    }
    ul {
        list-style: none;
    }
</style>

4、路由前后台交互

①生命周期钩子

前端点击页面要显示页面的信息,要从后端拿数据,那么什么时候拿,当页面一加载时就拿,这个时候就涉及到生命周期钩子

生命周期钩子:
    表示一个vue实例从创建到销毁的这个过程,将这个过程的一些时间节点赋予了对应的钩子函数
    钩子函数: 满足特点条件被回调的方法    
    new Vue({
        el: "#app",
        data: {
            msg: "message"
        },
        beforeCreate () {
            console.log("实例刚刚创建");
            console.log(this.msg
                        
        },
        created () {
            console.log("实例创建成功, data, methods已拥有");
            console.log(this.msg);
        },
        mounted () {
            console.log("页面已被vue实例渲染, data, methods已更新");
        }
        拿到需求 => 确定钩子函数 => 解决需求的逻辑代码块
    })        
开始创建的时候往后端发送请求,发送请求完渲染得到之后在mouted做数据替换            

②如何前后端交互?去创建一个Django项目

首先在Vue项目中
    安装 axios(ajax)的命令
        npm install axios --save
    为项目配置全局axios
        import Axios from 'axios'
        Vue.prototype.$ajax = Axios

③配置完成之后开始请求后端,写完之后开始在后端写路由接口

<template>
    <div class="goods">
        <h1>商品页</h1>
        <h2>{{ msg }}</h2>
    </div>
</template>

<script>
    export default {
        name: "Goods",
        data: function() {
            return {
                msg: ''
            }
        },
        beforeCreate() {
            window.console.log('开始创建Goods组件')
        },
        created() {
            window.console.log('创建Goods组件完毕')
        },
        mounted() {
            window.console.log('Goods组件渲染完毕');
            // 请求后台
            let _this = this;
            this.$ajax({
                method: 'post',
                url: ' http://127.0.0.1:8000/goods/',
                params: {
                    info: '前台数据'
                }
            }).then(function (result) {
                let data = result.data;
                // this 指向的是then的function
                _this.mas = data
            })

        }
    }
</script>

<style scoped>
    .goods {
        height: 100vh;
        background-color: pink;
    }
</style>
Vue前端
def goods(request):
    print(request.method)  # POST
    # axios的请求不管是get请求还是post请求,前端把所有的数据都解析到GET里,原生Django在GET里拿数据
    print(request.GET)     # <QueryDict: {'info': ['前台数据']}>
    print(request.POST)    # <QueryDict: {}>
    return HttpResponse('后端数据')
Django后端

④前端和后端在交互的过程中会出现跨域问题:

A网页访问B服务器资源时,不满足以下三个条件其一就是跨域访问
    1. 协议不同
    2. 端口不同
    3. 主机不同

Django解决跨域:
    1、安装django-cors-headers模块
    2、在settings.py中配置
        注册app
        INSTALLED_APPS = [
        'corsheaders'    
        ]
    3、添加中间件
        MIDDLEWARE = [
        'corsheaders.middleware.CorsMiddleware'
        ]
    4、允许跨域源
        CORS_ORIGIN_ALLOW_ALL = True

⑤最后两者能够正常的交互,需要注意的是

axios的请求不管是get请求还是post请求,前端把所有的数据都解析到GET里,原生Django在GET里拿数据

 

猜你喜欢

转载自www.cnblogs.com/zhangguosheng1121/p/11105328.html