vue學習 自建服務器 node

一、什麼是node
1.1 用C++語言編寫,用來運行JavaScript語言
1.2 node能夠爲前端項目提供server (包含了socket)

  

二、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    基本上是因爲網速的問題

  

即搭建一個vue環境的三步:
一、安裝node:  https://nodejs.org/zh-cn/

二、安裝cnpm:   npm install -g cnpm --registry=https://registry.npm.taobao.org

三、安裝vue/cli 3.x :  cnpm install -g @vue/cli

四、若是報錯處理後從新走2,3步,須要注意清除已安裝的環境: npm cache clean --force


查看終端安裝的vue和node的環境:

    vue: 直接輸入vue便可,有反應表明安裝完成

    node: 直接輸入node -v, 查看版本, 一樣存在反應即表明安裝完成javascript

 

 

 

 

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項目裏,須要安裝 多種插件html

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()
相關文章
相關標籤/搜索