1. 程式人生 > 實用技巧 >前後端分離的web專案-前端-nuxt+elementui

前後端分離的web專案-前端-nuxt+elementui

目錄

工具
流程
1. 建立專案
```shell
C:\Users\warm9>D:
D:\>yarn create nuxt-app demo03
```
2. 目錄結構
```text
專案     
|-- assets  //用於組織未編譯的靜態資源     
|-- components     //用於組織應用的vue.js元件       
|-- layouts        //佈局元件      
|-- middleware     //中介軟體       
|-- node_modules       
|-- pages      //檢視頁面      
|-- plugins      //外掛      
|-- static     //靜態資源      
|-- store      //狀態管理      
|-- test       
|-- .nuxt.config.js        //配置檔案        
|-- package.json       
```
3. 配置圖示
```markdown
|-- static
   |--favicon.ico
```
4. axios
- 配置
    ```markdown
    package.json檔案
   
      modules: [
        '@nuxtjs/axios','@nuxtjs/proxy'
      ],
      axios: {
          proxy: true, // 表示開啟代理
          prefix: '/api/', // 表示給請求url加個字首 /api
          credentials: true // 表示跨域請求時是否需要使用憑證
      },
      proxy: {
        '/api/': {
          target: 'http://localhost:8080', // 目標介面域名
          changeOrigin: true, // 表示是否跨域
          pathRewrite: {
            '^/api/': '/', // 把 /api 替換成 /
          }
        },
        '/webSocket':{
          target: 'http://localhost:8080', // 目標介面域名
          ws:true,
          changeOrigin: true, // 表示是否跨域
        }
      },
    ```
- 使用
    ```javascript
    this.$axios.get('/users/get_info').then(res=>{
          if(res.data.state==200){
            this.$store.commit('user/set',res.data.data.username)
            this.$store.commit('user/set_id',res.data.data.uid)
            this.$router.push('/home')
            this.$message(res.data.data.uid)
          }else{
            this.$router.push('/login')
          }
        })
    let param = new URLSearchParams
    param.append('所需引數','值')
    this.$axios.post("/api/task/ids",param).then(res=>{
          if(res.data.state===200){
              alert('建立成功!')
          }else{
              alert(res.data.message)
          }
        }).catch(function (e) {
        console.log(e)
    })
    ```
5. 檢視頁面
```markdown
|-- pages
   |-- 檢視(頁面)名.vue
```
6. 佈局頁面
```markdown
|-- layouts
   |-- 佈局名.vue
```
  • 用法
     /*檢視頁面*/
     export default {
          name: "檢視名稱",
          layout:"佈局名稱",     
     }
    
7. websocket連線
```javascript
export default {
      data(){
          return{
              socket: '',
          }
      },
      methods: {
        init :function(){
            if('WebSocket' in window){
                let wsServer = `${location.protocol === 'https' ? 'wss' : 'ws'}://${location.host}/webSocket/`;
                this.socket = new WebSocket(wsServer+this.uid)
                this.socket.onopen=this.onopen
                this.socket.onerror=this.onerror
                this.socket.onmessage=this.onmessage
                this.socket.onclose=this.onclose
            }else{
                alert("無法連線,請更換瀏覽器!")
            }
        },
        //連線
        onopen : function(){
            console.log("連線成功!")
        },
        //異常
        onerror:function(){
          console.log("連線失敗!")
        },
        //接受資訊
        onmessage:function(event){
          //彈窗資訊方法
          this.$message(event.data)
        },
        //關閉
        onclose:function(){
          console.log("關閉連線!")
        }
      },
      mounted() {
        this.init()
        //頁面關閉前關閉websocket
        window.addEventListener('beforeunload',()=>{if(this.socket)this.socket.close()})
      },
  }
```
8. 狀態管理
- 初始
    ```textmate
    |-- store
      |-- user.js
    ```
    ```javascript
    const state = ()=>({
      uid:"",
      username : ""
    })
    
    const mutations = {
      set(state,username){
        state.username = username
      },
      set_id(state,uid){
        state.uid = uid
      }
    }
    const actions = {
      nuxtServerInit({commit},req){
          console.log(1)
          console.log(req.session)
      }
    }
    export default {
      state,
      mutations,
      actions
    }
    ```
- 引用
    ```html
      <div>{{username}}}</div>
      <script>
          export default {
                computed:{
                  info(){
                      return this.$store.state.infos.infos | 0
                  },
                  username(){
                      return this.$store.state.user.username
                  },
                  uid(){
                      return this.$store.state.user.uid
                  }
              },
          }
     </script>
    ```  
- 修改
    ```javascript
    //第一個引數:狀態js的名稱/mutations中的方法;第二個引數:對應的修改後值
    this.$store.commit("user/set","value")
    ```  
9. 路由的使用
```javascript
//引數為檢視頁面名稱
this.$router.push('/login')
```
10. 狀態監測
```
watch:{
     "$store.state.user.uid" : function() {
       
     }
  }
```
11. hosts配置(主機域名)
- 路徑
    ```markdown
    |-- C:
      |-- Windows
          |-- System32
              |-- drivers
                  |-- etc
                      |-- hosts
    ```
- 新增內容
    ```markdown
    127.0.0.1       域名
    ```
12. nginx 部署
- 配置
    ```markdown
    |--conf
        |--nginx.conf
    ```
    - 內容
        ```markdown
        map $http_upgrade $connection_upgrade {
            default upgrade;
            ''      close;
        }
        server{
          listen       埠;
          server_name 域名;
          location / {
                proxy_pass  http://127.0.0.1:3001;
            }
      
        #nginx配置websocket
            location ^~ /webSocket {
                proxy_pass http://127.0.0.1:8080; #websocket地址
                proxy_http_version 1.1;
                proxy_set_header Host $host;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_read_timeout 120s;
     
                proxy_set_header Upgrade websocket;
                proxy_set_header Connection Upgrade;
            }
        }
        ```