vue学习 自建服务器 node

1、什么是node
1.1 用C++语言编写,用来运行JavaScript语言
1.2 node可以为前端项目提供server (包含了socket)

  

2、npm:包管理器 - 为node拓展功能的
在官网下载安装后


 换国内源,加速下载
管理员命令行:npm install -g cnpm --registry=https://registry.npm.taobao.org
MacOS/linux: sudo npm install -g cnpm --registry=https://registry.npm.taobao.org

所以npm的指令都可以换成cnpm   上述操作后
npm install vuex => cnpm install vuex

 

3.vue cli环境:脚手架 - 命令行快速创建项目

cnpm install -g @vue/cli   安装脚手架

如果报错:npm cache clean --force    基本上是由于网速的问题

  

4.创建Vue项目

1.cd 到目标目录
2.创建项目:vue create 目录名
剩余操作:

2.1  弹出下列对话框
?  Your connection to the default npm registry seems to be slow.
   Use https://registry.npm.taobao.org for faster installation? (Y/n)
	建议选择大写的Y  ,即国内的淘宝源

2.2 弹出对话框
Vue CLI v3.8.4
? Please pick a preset: (Use arrow keys)
> default (babel, eslint)
  Manually select features
  安装上下键切换,选择自定义的,也就是 Manually

2.3 回车进入自定义配置
>(*) Babel                         将es6转变为es5
 ( ) TypeScript                         比javascript更高级一点   
 ( ) Progressive Web App (PWA) Support    优化前端项目的功能组合
 (*) Router                      页面之间的转换,即 路由
 (* ) Vuex                         组件间信息交互,单例模式传值
 ( ) CSS Pre-processors           预编译语言
 (*) Linter / Formatter            格式化前端代码,规定代码格式
 ( ) Unit Testing                  用于测试
 ( ) E2E Testing					用于测试									

2.4 弹出对话:
Vue CLI v3.8.4
? Please pick a preset: Manually select features
? Check the features needed for your project: Babel, Router, Vuex, Linter
? Use history mode for router? (Requires proper server setup for index fallback in production) (Y/n)
"""
是否产生历史记录给路由,历史记录是两个页面之间的转跳才产生,加上后,可以实现页面的前进与后退
选择Y  即可


2.5 弹出对话框
> ESLint with error prevention only
  ESLint + Airbnb config
  ESLint + Standard config
  ESLint + Prettier
 选择第一个即可

2.6 弹出对话框
? Pick a linter / formatter config: Basic
? Pick additional lint features: (Press <space> to select, <a> to toggle all, <i> to invert selection)
>(*) Lint on save
 ( ) Lint and fix on commit (requires Git)  在git里保存 管理
   选择第一个即可
    
2.7 对话框
? Where do you prefer placing config for Babel, PostCSS, ESLint, etc.? (Use arrow keys)
> In dedicated config files
  In package.json
选择第一个,小规律,没有大小写推荐的话,默认选择第一个更合适
 
2.8 对话框
? Where do you prefer placing config for Babel, PostCSS, ESLint, etc.? In dedicated config files
? Save this as a preset for future projects? (y/N)
保存这次的配置,下次生成的时候自动使用,因此不建议选择y,此处选择N

上述配置完后,就自动创建项目

  

5.启动项目


""" 终端启动  类似于django的项目创建后在命令行的启动
1.进入项目:cd到项目目录  即找到你所创建的项目名,而非上一级的目录
2.启动项目:npm run serve   也可以将npm替换为cnpm
弹出两个地址:
App running at:
- Local:   http://localhost:8080/    本机地址
- Network: http://192.168.11.108:8080/  ip+端口

"""

""" pycharm配置后启动
在pycharm里找到创建的vue项目,打开
1.下载vue.js插件,重启
2.配置项目里 + 号下的的npm启动项  找到npm, 
2.1  选择package.json 为创建好的package.json即可
2.2 scripts  选择为serve 即可
2.3 可以改变其默认的名字
3.点击导航栏内的三角形按钮启动,即可
"""

只要改变了数据,只需按下 ctrl+s 保存即可实现页面的刷新

  

6.重点    vue项目的重构

 去到c盘根目录:在终端敲下  cd ../..  即可

vue项目的重构:去掉node_modules依赖和idea文件,将其他的文件复制到另一文件下,在终端通过找到对应的路径下的项目,输入 npm install 来实现根据电脑环境来配置好项目。

然后通过pycharm打开该文件,按照上述配置操作后就可以正常使用vue了

  

7.项目目录

"""
node_modules:依赖
public:共有资源
	ico:页面标签的logo
	html:单页面 - 整个项目的唯一页面
src:代码主体
...:项目、插件等相关配置
"""

""" src
assets:静态资源
components:小组件
views:视图组件  页面组件
App.vue:根组件
main.js:主脚本文件
router.js:路由脚本文件 vue-router
store.js:仓库脚本文件 vuex
"""

  

8.组件

<template>
    <!-- 只能有一个根标签 -->
</template>

<script>
    export default {  //  导出
        name: "Main",
        data: function() {
            return {
                
            }
        },
        ...
    }
</script>

<style scoped>
	/* scoped */   // 一个页面的样式应该对应一个页面,不加实现不了样式的局部化  跟组件的样式适用于所有,而此处的样式只适合这个页面
</style>

  

9.在根组件中渲染页面组件




<!-- 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>

  

10. 路由:router.js   实现切换多个 小块,不刷新



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

<template>
  <div id="app">
   <ul class="nav " >
     <li><router-link to="/">主页</router-link></li>   
     <li><router-link to="/goods/">商品页</router-link></li>
     <li><router-link to="/people/">个人页</router-link></li>
   </ul>

    <router-view/>   <!--渲染-->  
  </div>
</template>
				/*  类似于a标签,比a标签更高级     */


<style>
li  {
    float: left;
    height: 60px;
    width: 120px;
    text-align: center;
    line-height: 60px;
  }
li:hover {
    background-color: coral;
  }
  
li a {
    text-decoration: none;        /*  去除a标签的下划线 */
    font: bold 30px/60px 'STSong';      /* 加粗  字体30px 行高60px 字体样式*/
  }

</style>



2.创建三个页面组件     Main.vue      Goods.vue      People.vue


<template>
    <div class="goods">    /* main   people  */
        <h1>商品页</h1>
    </div>
</template>

<script>
    export default {
        name: "Goods"    /* main   people  */
    }
</script>

<style scoped>
 .goods {
        height: 100vh;
        background-color: pink;

    }
</style>



3.配置路由    router.js


import Main from './views/Main.vue'
import Goods from './views/Goods.vue'
import People from './views/People.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: '/people',
      name: 'people',
      component: People
    },

  ]
})

  

11.生命周期钩子


- 表示一个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 () {
        // 在此函数的返回函数里,this代表的是现在的返回函数,而不是全局 的
        console.log("页面已被vue实例渲染, data, methods已更新");
    }
    // 拿到需求 => 确定钩子函数 => 解决需求的逻辑代码块
})    
    
    

  

Django跨域问题

什么是跨域

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

  

Django解决跨域


安装django-cors-headers模块
pip3 install -i https://pypi.douban.com/simple django-cors-headers


在settings.py中配置
# 注册app
INSTALLED_APPS = [
	...
	'corsheaders'
]
# 添加中间件
MIDDLEWARE = [
	...
	'corsheaders.middleware.CorsMiddleware'
]
# 允许跨域源
CORS_ORIGIN_ALLOW_ALL = True

  

在vue项目里,需要安装 多种插件

vue-router


{
    path: '/',
    name: 'home',
    // 路由的重定向
    redirect: '/home'
}

{
    // 一级路由, 在根组件中被渲染, 替换根组件的<router-view/>标签
    path: '/one-view',
    name: 'one',
    component: () => import('./views/OneView.vue')
}

{
    // 多级路由, 在根组件中被渲染, 替换根组件的<router-view/>标签
    path: '/one-view/one-detail',
    component: () => import('./views/OneDetail.vue'),
    // 子路由, 在所属路由指向的组件中被渲染, 替换该组件(OneDetail)的<router-view/>标签
    children: [{
        path: 'show',
        component: () => import('./components/OneShow.vue')
    }]
}

  

补充:  


<!-- router-link渲染为a标签 -->
<router-link to="/">Home</router-link> |
<router-link to="/about">About</router-link> |
<router-link :to="{name: 'one'}">One</router-link> |

<!-- 为路由渲染的组件占位 -->
<router-view />


a.router-link-exact-active {
    color: #42b983;
}



// router的逻辑转跳
this.$router.push('/one-view')

// router采用history方式访问上一级
this.$router.go(-1)

  

vuex

// 在任何一个组件中,均可以通过this.$store.state.msg访问msg的数据
// state永远只能拥有一种状态值
state: {
    msg: "状态管理器"
},
// 让state拥有多个状态值
mutations: {
    // 在一个一个组件中,均可以通过this.$store.commit('setMsg', new_msg)来修改state中的msg
    setMsg(state, new_msg) {
        state.msg = new_msg
    }
},
// 让mutations拥有多个状态值
actions: {

}

  

vue-cookie

// 安装cookie的命令
// npm install vue-cookie --save
// 为项目配置全局vue-cookie
import VueCookie from 'vue-cookie'
// 将插件设置给Vue原型,作为全局的属性,在任何地方都可以通过this.$cookie进行访问
Vue.prototype.$cookie = VueCookie




// 持久化存储val的值到cookie中
this.$cookie.set('val', this.val)
// 获取cookie中val字段值
this.$cookie.get('val')

  

axios


// 安装 axios(ajax)的命令
// npm install axios--save
// 为项目配置全局axios
import Axios from 'axios'
Vue.prototype.$ajax = Axios    // 后面就可以直接通过this找到这个全局的变量了



let _this = this
this.$ajax({
    method: 'post',
    url: 'http://127.0.0.1:5000/loginAction',
    params: {
        usr: this.usr,
        ps: this.ps
    }
}).then(function(res) {
    // this代表的是回调then这个方法的调用者(axios插件),也就是发生了this的重指向
    // 要更新页面的title变量,title属于vue实例
    // res为回调的对象,该对象的data属性就是后台返回的数据
    _this.title = res.data
}).catch(function(err) {
    window.console.log(err)
})

  

# 用pycharm启动该文件模拟后台
from flask import Flask, request, render_template
from flask_cors import CORS
app = Flask(__name__)
CORS(app, supports_credentials=True)

@app.route('/')
def index():
    return "<h1>主页</h1>"

@app.route('/loginAction', methods=['GET', 'POST'])
def test_action():
    # print(request.args)
    # print(request.form)
    # print(request.values)
    usr = request.args['usr']
    ps = request.args['ps']
    if usr != 'abc' or ps != '123':
        return 'login failed'
    return 'login success'


if __name__ == '__main__':
    app.run()

  

 

猜你喜欢

转载自www.cnblogs.com/changwenjun-666/p/11104881.html