vue+nodejs+mongodb 項目開發全過程

vue項目

前端

使用vue-cli快速生成項目文檔。javascript

腳手架搭建

一、安裝全局vue-cliphp

npm install --global vue-cli

二、使用腳手架建立項目文檔css

vue init webpack vuetest

項目目錄

your project
    client/     #前端文檔
    server/     #後臺文檔
    note/       #說明文檔

建立組件,視圖 以home頁爲例

一、在src文件夾中建立view文件夾,在view文件夾中建立home.vue組件html

二、home.vue的內容格式以下:前端

<template>

    #添加你的html內容,須要使用一個閉合的標籤包裹,例如:
    <div>
        <nav-header></nav-header>  
        //···
        <nav-footer></nav-footer>
    </div>

</template>

<script>
//導入外部引入的css樣式
import '../../static/css/index.css'
//導入子組件
import NavHeader from '../components/NavHeader'
import NavFooter from '../components/NavFooter'
import NavCrumbs from '../components/NavCrumbs'

export default {    # 導出讓其餘地方可使用
    name: 'Home',
    data () {       # 組件中數據要寫成閉包的形式
        return {
            msg: 'Welcome to Your Vue.js App'
        }
    },
    components: {   #引用子組件
        NavHeader,
        NavFooter,
        NavCrumbs
    }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
    # 添加該組件本身的css樣式
</style>

三、子組件:把header和footer作成子標籤,這樣能夠在其餘頁面使用。vue

配置路由

在router/index.js文件中配置:java

import Vue from 'vue'               # 導入vue
import Router from 'vue-router'     # 使用vue-router插件
import Home from '@/views/Home'     # 導入組件
//···其餘組件

Vue.use(Router)

export default new Router({
    routes: [
    {
        path: '/',
        name: 'Home',
        component: Home
    },
    //···其餘組件
    ]
})

在組件中使用路由實現單頁切換

使用 router-link標籤,經過to 屬性添加要切換的路由,"/"表示根路由,若是沒有則表示當前路由(能夠用在子路由)node

<router-link class="link" to="/login" rel="nofollow" >登陸</router-link>

router-link默認映射爲標籤,固然能夠改,除了to屬性,其餘屬性能夠根據本身的須要添加mysql

在vue中圖片懶加載詳細介紹

說明

當網絡加載比較慢的時候,webpack

使用

使用vue的vue-lazyload,地址:https://www.npmjs.com/package...

安裝

npm/cnpm

$ npm install vue-lazyload/$ cnpm install vue-lazyload

CDN

CDN:https://unpkg.com/vue-lazyloa...

<script src="https://unpkg.com/vue-lazyload/vue-lazyload.js"></script>
<script>
  Vue.use(VueLazyload)
  ...
</script>

如何使用

在入口文件main.js中:

import Vue from 'vue'
import App from './App.vue'
import VueLazyload from 'vue-lazyload'
 
Vue.use(VueLazyload)
 
// or with options
Vue.use(VueLazyload, {
  preLoad: 1.3,
  error: 'dist/error.png',
  loading: 'dist/loading.gif',
  attempt: 1
})
 
new Vue({
  el: 'body',
  components: {
    App
  }
})

在組件中使用:把項目組件中的須要懶加載的 :src換成v-lazy,例如:

<div class="pic">
    <a href="#"><img :src="'static/img/'+item.productImage" alt=""></a>
</div>

替換後

<div class="pic">
    <a href="#"><img v-lazy="'static/img/'+item.productImage" alt=""></a>
</div>

後端

使用express-generator生成項目

nodejs+mysql項目搭建
參考express 建立項目詳解

mongodb安裝、配置、使用

mongodb教程,
mongodb下載
mongoose

可視化工具:mongobooster

MongoDB 是一個基於分佈式文件存儲的數據庫。由 C++ 語言編寫。旨在爲 WEB 應用提供可擴展的高性能數據存儲解決方案。

MongoDB 是一個介於關係數據庫和非關係數據庫之間的產品,是非關係數據庫當中功能最豐富,最像關係數據庫的。

數據庫連接

// 鏈接數據庫 若是不本身建立 默認test數據庫會自動生成
mongoose.connect('mongodb://localhost:27017/shop');

添加監聽事件

// 爲此次鏈接綁定事件
const db = mongoose.connection;
// 數據庫連接錯誤監聽
db.once('error', () => console.log('Mongo connection error'));
// 數據庫連接成功監聽
db.once('open', () => console.log('Mongo connection successed'));
// 數據庫關閉監聽
db.once('close', () => console.log('Mongo connection faild'));

模塊導出

module.exports = router;

文檔代碼

var express = require('express');
var router = express.Router();
//導入mongoose插件
var mongoose = require('mongoose');

// 鏈接數據庫 若是不本身建立 默認test數據庫會自動生成
mongoose.connect('mongodb://localhost:27017/shop');

// 爲此次鏈接綁定事件
const db = mongoose.connection;
db.once('error', () => console.log('Mongo connection error'));
db.once('open', () => console.log('Mongo connection successed'));
db.once('close', () => console.log('Mongo connection faild'));

// 導入集合模塊
var Goods = require("../modules/goods");

/* GET goods listing. */
router.get('/', function(req, res, next) {
    res.send('respond with a resource');
});
//添加本身的路由
//···
module.exports = router;

集合模塊代碼

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

// 使用 module.exports 導出 模塊
module.exports = mongoose.model("Goods", new Schema({
    productId: String,
    productName: String,
    salePrice: Number,
    productImage: String,
    productUrl: String
    //···
}))

路由配置

在app.js文件中完成路由配置,首先導入

var goods = require('./routes/goods');

而後

app.use('/goods', goods);

添加二級路由

router.get('/list', function(req, res, next) {
    res.send('respond with a resource');
    //添加數據庫操做
    //···
});

數據庫操做

查詢數據並排序輸出

在MongoDB中使用使用sort()方法對數據進行排序,sort()方法能夠經過參數指定排序的字段,並使用 1 和 -1 來指定排序的方式,其中 1 爲升序排列,而-1是用於降序排列。
sort(mongoose文檔)
sort菜鳥教程

//使用價格排序
Goods.find({}).sort({ 'salePrice': sort })
    .exec(function(err, result) {
        //···
    })

按照範圍查找使用 $gte/$gt 和 $lte/$lt

mongodb條件操做符,
條件操做符用於比較兩個表達式並從mongoDB集合中獲取數據。MongoDB中條件操做符有:

(>) 大於 - $gt
(<) 小於 - $lt
(>=) 大於等於 - $gte
(<= ) 小於等於 - $lte

使用方式

Goods.find({"likes" : {$gt : 100}}).exec(function(err,result){
    //···
})

限制查詢數量limit()

若是你須要在MongoDB中讀取指定數量的數據記錄,可使用MongoDB的Limit方法,limit()方法接受一個數字參數,該參數指定從MongoDB中讀取的記錄條數。

使用方式

Goods.find({"likes" : {$gt : 100}}).limit(8)
    .exec(function(err,result){
        //···
    })

跳過指定數量的數據skip()

咱們除了可使用limit()方法來讀取指定數量的數據外,還可使用skip()方法來跳過指定數量的數據,skip方法一樣接受一個數字參數做爲跳過的記錄條數。skip()方法默認參數爲 0 。

使用方式

Goods.find({"likes" : {$gt : 100}}).limit(8).skip(0)
    .exec(function(err,result){
        //···
    })

路由代碼詳情

router.get('/list', function(req, res, next) {

    let sort = req.query.sort || 1;
    let minPrice = req.query.minPrice || null;
    let maxPrice = req.query.maxPrice || null;
    let price = {};
    // 篩選
    if (minPrice && maxPrice) {
        price = { salePrice: { $gte: minPrice, $lte: maxPrice } }
    } else if (minPrice && !maxPrice) {
        price = { salePrice: { $gte: minPrice } }
    } else if ((!minPrice) && maxPrice) {
        price = { salePrice: { $lte: maxPrice } }
    } else {
        price = {}
    }
    console.log(price)
        // sort()排序, limit()限制查詢數量
    Goods.find(price).sort({ 'salePrice': sort }).limit(8)
        .exec(function(err, result) {
            if (err) {
                res.json({
                    status: 1,
                    msg: err.message
                })
            } else {
                res.json({
                    status: 0,
                    msg: "查詢成功",
                    data: result
                })
            }
        })

});
2017年10月23日20:57:46
2017年10月24日09:36:36

vue-infinite-scroll 瀑布流加載

vue-infinite-scroll

安裝

npm install vue-infinite-scroll --save

CommonJS使用方式

You can use any build tool which supports commonjs:

// register globally
var infiniteScroll =  require('vue-infinite-scroll');
Vue.use(infiniteScroll)
 
// or for a single instance
var infiniteScroll = require('vue-infinite-scroll');
new Vue({
  directives: {infiniteScroll}
})

ES2015 使用方式

// register globally
import infiniteScroll from 'vue-infinite-scroll'
Vue.use(infiniteScroll)
 
// or for a single instance
import infiniteScroll from 'vue-infinite-scroll'
new Vue({
  directives: {infiniteScroll}
})

在組件中使用

在template中須要的位置插入

<div v-infinite-scroll="loadMore" infinite-scroll-disabled="busy" infinite-scroll-distance="10">
  ...
</div>

在script中:

var count = 0;
 
new Vue({
  el: '#app',
  data: {
    data: [],
    busy: false
  },
  methods: {
    loadMore: function() {
      this.busy = true;
 
      setTimeout(() => {
        for (var i = 0, j = 10; i < j; i++) {
          this.data.push({ name: count++ });
        }
        this.busy = false;
      }, 1000);
    }
  }
});

vue-lazyload 圖片懶加載

vue-lazyload

安裝

$ npm install vue-lazyload

配置

在main.js中導入

import VueLazyload from 'vue-lazyload'
Vue.use(VueLazyload)

使用方式

<script>
export default {
  data () {
    return {
      imgObj: {
        src: 'http://xx.com/logo.png',
        error: 'http://xx.com/error.png',
        loading: 'http://xx.com/loading-spin.svg'
      },
      imgUrl: 'http://xx.com/logo.png' // String
    }
  }
}
</script> 
 
<template>
  <div ref="container">
     <img v-lazy="imgUrl"/>
     <div v-lazy:background-image="imgUrl"></div>
 
     <!-- with customer error and loading -->
     <img v-lazy="imgObj"/>
     <div v-lazy:background-image="imgObj"></div>
 
     <!-- Customer scrollable element -->
     <img v-lazy.container ="imgUrl"/>
     <div v-lazy:background-image.container="img"></div>
 
    <!-- srcset -->
    <img v-lazy="'img.400px.jpg'" data-srcset="img.400px.jpg 400w, img.800px.jpg 800w, img.1200px.jpg 1200w">
    <img v-lazy="imgUrl" :data-srcset="imgUrl' + '?size=400 400w, ' + imgUrl + ' ?size=800 800w, ' + imgUrl +'/1200.jpg 1200w'" />
  </div>
</template>

父組件調用子組件方法$refs 2017年10月27日11:23:37

<template>
    <div id="app">
        <input type="button" name="" id="" @click="parentCall" value="父調子" />
        <hello ref="chil" />//hello組件
    </div>
</template>

<script>
    import hello from './components/Hello'
    export default {
        name: 'app',
        'components': {
            hello
        },
        methods: {
          parentCall () {
            this.$refs.chil.chilFn('我是父元素傳過來的')
          }
        }
    }
</script>

/*Hello.vue  :*/

<template>
    <div class="hello"></div>
</template>

<script>
    export default {
        name: 'hello',
        'methods': {
         chilFn (msg) {
         alert(msg)
        }
        }
    }
</script>

錯誤Can't set headers after they are sent. 重複調用res.json({})

Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:356:11)
    at ServerResponse.header (D:\phpStudy\WWW\myproject\vnshop\server\node_modul                         es\_express@4.15.5@express\lib\response.js:730:10)
    at ServerResponse.json (D:\phpStudy\WWW\myproject\vnshop\server\node_modules                         \_express@4.15.5@express\lib\response.js:253:10)
    at D:\phpStudy\WWW\myproject\vnshop\server\controller\users\users.controller                         .js:691:36
    at Array.forEach (native)
    at D:\phpStudy\WWW\myproject\vnshop\server\controller\users\users.controller                         .js:689:34
    at Query.<anonymous> (D:\phpStudy\WWW\myproject\vnshop\server\node_modules\_                         mongoose@4.12.4@mongoose\lib\model.js:3932:16)
    at D:\phpStudy\WWW\myproject\vnshop\server\node_modules\_kareem@1.5.0@kareem                         \index.js:273:21
    at D:\phpStudy\WWW\myproject\vnshop\server\node_modules\_kareem@1.5.0@kareem                         \index.js:131:16
    at _combinedTickCallback (internal/process/next_tick.js:67:7)

解決方法

錯誤1

errmsg:"E11000 duplicate key error collection: shop.users index: addressList.addressId_1 dup key: { : null }"

解決方法

先運行 mongo 到 mongodb shell 命令行模式下,執行如下命令:

db.users.getIndexes(); //查看全部索引
db.users.dropIndex({"addressId":"1"});

而後未解決。。。。。。。

最後只能導入數據庫

接口文檔說明

待續····

服務器配置

購買服務器

版瓦工
阿里雲

註冊域名

阿里雲

服務器配置工具

安裝Xshell

使用方式

打開工具--->新建--->填寫(名稱,主機ip:······,端口號:29007)--->用戶認證(用戶(root)和密碼(本身設置))

開始配置lnmp

  1. apt-get update -y 對系統更新 出現Reading package lists... Done 算是成功

  2. apt-get install zsh git curl -y 加載安裝工具

  3. cat /etc/issue 查看系統版本,這裏使用Ubuntu 16.04

  4. sh -c "$(curl -fsSL https://raw.github.com/robbyr...)" 安裝zsh

  5. wget -c http://soft.vpser.net/lnmp/ln... && tar zxf lnmp1.4.tar.gz && cd lnmp1.4 && ./install.sh lnmp 安裝lnmp,

  6. 選擇數據庫版本默認就能夠

  7. 輸入數據庫密碼---輸入你的密碼(saigsf)

  8. 選擇MySQL數據庫引擎 ----輸入y或直接回車,默認選擇innoDB引擎

  9. PHP引擎選擇,默認5.5.38

  10. 選擇默認直接回車

  11. 按任意鍵開始安裝,Ctrl+c取消安裝.

  12. LNMP腳本就會自動安裝編譯Nginx、MySQL、PHP、phpMyAdmin、Zend Optimizer這幾個軟件。

  13. 安裝完成後,在瀏覽器中經過IP(http://69.171.77.35/)能夠看到...

安裝node

採用nvm安裝node:https://github.com/creationix...

安裝nvm腳本

試用如下兩種方式:

To install or update nvm, you can use the install script using cURL:

curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.6/install.sh | bash
or Wget:
wget -qO- https://raw.githubusercontent.com/creationix/nvm/v0.33.6/install.sh | bash

配置nvm環境變量

export NVM_DIR="$HOME/.nvm" 
[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" # This loads nvm
command -v nvm

安裝node

To download, compile, and install the latest release of node, do this:

nvm install node

And then in any new shell just use the installed version:

nvm use node

Or you can just run it:

nvm run node --version

Or, you can run any arbitrary command in a subshell with the desired version of node:

nvm exec 4.2 node --version

You can also get the path to the executable to where it was installed:

nvm which 5.0

安裝完成後,檢測

node -v

安裝mongoDB

  1. 導入公鑰

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 0C49F3730359A14518585931BC711F9BA15703C6
  1. Create a list file for MongoDB

echo "deb [ arch=amd64,arm64 ] http://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.4 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.4.list
  1. Reload local package database

sudo apt-get update
  1. Install the MongoDB packages

sudo apt-get install -y mongodb-org

Run MongoDB Community Edition

  1. Start MongoDB

sudo service mongod start
or
mongod --dbpath data/ --logpath log/mongodb.log -logappend --fork
  1. Verify that MongoDB has started successfully

[initandlisten] waiting for connections on port <port>

where <port> is the port configured in /etc/mongod.conf, 27017 by default.

  1. Stop MongoDB

sudo service mongod stop
  1. Restart MongoDB

sudo service mongod restart
  1. Begin using MongoDB

Uninstall MongoDB Community Edition

  1. Stop MongoDB

sudo service mongod stop
  1. Remove Packages

sudo apt-get purge mongodb-org*
  1. Remove Data Directories.

sudo rm -r /var/log/mongodb
sudo rm -r /var/lib/mongodb

配置mongod.conf文件

刪除綁定的IP,就能夠在遠程連接。

vim /etc/mongod.conf

vim 命令操做

    1. 插入,下方出現insert 就能夠編輯上面的信息

  1. esc 退出編輯

  2. :指令 對文件操做

  3. :wq 保存並退出

  4. :wq! 強制保存並退出

  5. :q 直接退出

  6. dd 刪除一行

  7. 10dd 刪除10行

2017年10月31日09:49:36

操做

查看端口信息

netstat -anp | grep 27017

查看日誌

cat /var/log/mongodb/mongod.log

上傳項目文件----方法一

  1. 生成dist文件夾,並壓縮爲zip格式

npm run build

npm run build是vue生成項目文件的語句

  1. 經過xshell上傳到服務器
    自動安裝lrzsz工具

    sudo apt-get install lrzsz

    rz,sz是Linux/Unix同Windows進行ZModem文件傳輸的命令行工具
    優勢:比ftp命令方便,並且服務器不用打開FTP服務。
    sz:將選定的文件發送(send)到本地機器
    rz:運行該命令會彈出一個文件選擇窗口,從本地選擇文件上傳到Linux服務器

  2. 執行rz語句,選擇壓縮文件,開始上傳

rz

在哪裏執行就會上傳到哪裏,選擇/home/wwwroot

  1. 解壓

unzip dist.zip
  1. 添加虛擬主機 ,詳情見下文,會生成一個文件夾

  2. 將解壓後的文件複製到指定目錄,cp:複製,-r:深度複製,*:全部文件

cp -r dist/* 目標文件夾

方法二----從github上拉取項目

  1. 建立虛擬主機····

  2. 拉取github項目文件

git clone https://github.com/saigsf/vnshop.git vnshop(文件夾名)
  1. 安裝淘寶鏡像

  2. 進入vnshop/client,進行初始化

cnpm i/npm i
  1. 執行build語句

npm run build
  1. 修改服務器配置文件

root 項目文件所在目錄dist
  1. 重啓服務器···OK

nodejs上線

  1. 項目拉取

git clone https://github.com/saigsf/vnshop.git vnshop(文件夾名)
  1. 安裝依賴

npm install
  1. 啓動測試

npm run start
  1. 使用pm2啓動服務

npm i pm2 -g

啓動

pm2 start ./bin/www
  1. 配置跨域,在項目文件中配置好生產環境和開發環境的訪問IP
    在 src/config/api.config.js

const isPro = Object.is(process.env.NODE_ENV == 'production');
module.exports = {
    baseURl: isPro ? 'http://vnshop.saigsf.com/api/' : 'api/'
}
  1. 配置反向代理,nginx配置執行:

vim /usr/local/nginx/conf/vhost/vnshop.saigsf.xyz.conf

而後添加

location /api/ {
    proxy_pass http://127.0.0.1:3000/; # 當訪問api的時候默認轉發到 3000端口
}

git webhook使用

webhooks容許外部服務時要通知某些事件發生在你的庫。當指定事件發生時,咱們將向您提供的每一個URL發送一個POST請求。瞭解更多咱們webhooks指南

  1. 在github項目倉庫,點擊setting----點擊webhooks---點擊add hook,輸入密碼肯定

  2. Payload URL 當咱們提交代碼後 git webhook會向這個url發送一個post請求

  3. Content type 選擇返回類型 (選擇json 類型)

  4. Secret 輸入密鑰 要和程序中的密鑰保持一致

  5. Which events would you like to trigger this webhook? 選擇要監聽的事件

 在一臺服務器上配置多個網站

使用Nginx虛擬化配置

操做步驟

  1. 執行lnmp vhost add,輸入本身要綁定的域名,在此以前要把域名解析到當前主機。

lnmp vhost add

回車綁定,若是輸入錯誤就按Ctrl+backspace 刪除

  1. 輸入本身域名對應的文件目錄,若是不更改直接回車,默認在/home/wwwroot/··· 以你的域名文件夾名字建立目錄,若是輸入了名字,要使用全路徑(加/的)。

  2. 是否要添加靜態規則 ,根據網站程序配置選擇,通常是url 的訪問格式

  3. 是否添加日誌,最好保存

  4. 是否選擇MySQL的表名,不用了謝謝~

  5. end···點擊任意鍵開始建立

重複以上操做建立多個網站

虛擬主機配置錯了怎麼改

vim /usr/local/nginx/conf/vhost/···.conf
  1. server_name 域名1 域名2 域名3 ···

  2. 首訪問文件 index index.html ···

修改配置文件都要重啓

service nginx restart

systemctl status nginx.service #查看狀態

/etc/init.d/nginx restart # 通常使用這個
相關文章
相關標籤/搜索