Vue+element+Nodejs學習記錄(5)

1.Vue基礎使用

vue-cli 3.x創建項目

npm install -g @vue/cli
vue create hello-world 或者 vue ui

cd 目錄
vue run serve

參考文章:https://www.cnblogs.com/niwalala/p/9253746.html

Vue中使用element

1.在項目根目錄執行命令:npm i element-ui -S進行安裝

2.在main.js中引入element:
import Element from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css';
Vue.use(Element)

3.然後在.vue文件裏就直接可以用了

參考文章:
https://blog.csdn.net/qq_37164847/article/details/80939741
https://www.cnblogs.com/yuyujuan/p/10267749.html

Vue中的跨域請求

因爲端口號不同,比如後端api接口可能是8000,Vue的端口是是8080,會涉及到跨域,所以我們要在vue.config.js中設置應該服務器代理。代碼如下:

proxyTable: {
  '/api': {                 //使用/api代理對3000端口服務的請求
    target: 'http://localhost:3000',
    changeOrigin: true,
    pathRewrite: {
      '^/api': '/api'
    }
  },
},

也可以在服務端設置CORS進行跨域。

router-link和router-view

<template>
	
  <div id="app">

    <div id="nav">
     <!-- 使用 router-link 組件來導航. -->
     <!-- 通過傳入 `to` 屬性指定鏈接. -->
     <!-- <router-link> 默認會被渲染成一個 `<a>` 標籤 -->
      <router-link to="/"></router-link>
    </div>

    <keep-alive>
		<!-- 路由出口 -->
  		<!-- 路由匹配到的組件將渲染在這裏 --> 		   
    	<router-view/>
    </keep-alive>

  </div>

</template>

<style scoped>

</style>

// '/'路由對應Home組件,所以Home組件內容將會渲染到router-view部分
export default new Router({
  routes: [
    {
		path: '/',
		name: 'Home',
		component: Home,
    },
    {
		path:'/city',
		name:'City',
		component: City
    },
    {
    	//動態路由,前面是/detail後面帶一個參數,放入id變量中
    	path:'/detail/:id',
    	name:'Detail',
    	component:Detail

    }
  ],
  scrollBehavior(to,from,savedPosition){
    return {x:0,y:0}
  }
});

2.Vue router、Axios、Vuex使用

我們需要弄懂這幾個常用的概念。

Vue router

使用 Vue.js 做項目的時候,一個頁面是由多個組件構成的,所以在跳轉頁面的時候,並不適合用傳統的 href,於是 vue-router 應運而生。

對於router-link和router-view上面解釋了,使用Vue router創建好router.js文件後,就可以使用router-link和router-view進行頁面跳轉了。

//router.js
import Home from './components/home.vue'

const routers = [
  {
    path: '/home',
    name: 'home',
    component: Home
  },
  {
    path: '/',
    component: Home
  },
]
export default routers

這種只需要跳轉頁面,不需要添加驗證方法的情況,可以使用router-link來實現導航

在這裏插入圖片描述

在編譯之後,<router-link>會被渲染爲<a>標籤, to 會被渲染爲 href,當<router-link>被點擊的時候,url 會發生相應的改變。

實際情況下,有很多按鈕在執行跳轉之前,還會執行一系列方法,這時候可以使用this.$router.push(location)來修改url,完成跳轉

在這裏插入圖片描述
在這裏插入圖片描述

axios

Vue 原本有一個官方推薦的 ajax 插件 vue-resource,但是自從 Vue 更新到 2.0 之後,官方就不再更新 vue-resource,目前主流的 Vue 項目,都選擇 axios 來完成 ajax 請求。

//axios get請求
axios.get("/user?ID=12345")
    .then(function(res){//成功執行的函數
    	console.log(res)
	})
    .catch(function(err){//失敗執行的函數
    	console.log(err);
	})

//axios  post請求
axios.post("/user",{
    firstName:'志武',
    lastName:"胡"
})
    .then(function(res){
    	console.log(res);
	})
    .catch(function(err){
    	console.log(err)
	})

Vuex

Vuex 應用的狀態 state 都應當存放在 store.js 裏面,Vue 組件可以從 store.js 裏面獲取狀態,可以把 store 通俗的理解爲一個全局變量的倉庫。

但是和單純的全局變量又有一些區別,主要體現在當 store 中的狀態發生改變時,相應的 vue 組件也會得到高效更新。

在 src 目錄下創建一個 vuex 目錄,將 store.js 放到 vuex 目錄下

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
  // 定義狀態
  state: {
    author: 'Wise Wrong'
  }
})

export default store

將狀態映射到組件

<template>
  <footer class="footer">
    <ul>
      <li v-for="lis in ul">{{lis.li}}</li>
    </ul>
    <p>
      Copyright&nbsp;&copy;&nbsp;{{author}} - 2016 All rights reserved
    </p>
  </footer>
</template>

<script>
  export default {
    name: 'footerDiv',
    data () {
      return {
        ul: [
          { li: '琉璃之金' },
          { li: '朦朧之森' },
          { li: '縹緲之滔' },
          { li: '逍遙之火' },
          { li: '璀璨之沙' }
        ]
      }
    },
    computed: {
      author () {
        return this.$store.state.author
      }
    }
  }
</script>

這是 footer.vue 的 html 和 script 部分,主要在 computed 中,將 this.$store.state.author 的值返回給 html 中的 author,頁面渲染之後,就能獲取到 author 的值。

在組件中修改狀態

然後在 header.vue 中添加一個輸入框,將輸入框的值傳給 store.js 中的 author

這裏我使用了 Element-UI 作爲樣式框架

在這裏插入圖片描述

上面將輸入框 input 的值綁定爲 inputTxt,然後在後面的按鈕 button 上綁定 click 事件,觸發 setAuthor 方法

methods: {
 setAuthor: function () {
   this.$store.state.author = this.inpuTxt
 }
}

在 setAuthor 方法中,將輸入框的值 inputTxt 賦給 Vuex 中的狀態 author,從而實現子組件之間的數據傳遞。

官方推薦的修改狀態的方式

上面的示例是在 setAuthor 直接使用賦值的方式修改狀態 author,但是 vue 官方推薦使用下面的方法:

在這裏插入圖片描述

首先在 store.js 中定義一個方法 newAuthor,其中第一個參數 state 就是 $store.state,第二個參數 msg 需要另外傳入

然後修改 header.vue 中的 setAuthor 方法

在這裏插入圖片描述

這裏使用 $store.commit 提交 newAuthor,並將 this.inputTxt 傳給 msg,從而修改 author

這樣顯式地提交(commit) mutations,可以讓我們更好的跟蹤每一個狀態的變化,所以在大型項目中,更推薦使用第二種方法。

Vuex狀態管理流程:view——action——mutations——state——views

1.mutations直接改變state的數據

var store = new Vuex.Store({
    state:{
        name:"胡志武"
    },
    mutations:{
    //這裏傳入的是state	
		change(state){
			state.name="志武胡"
		}
})


//調用
this.$store.commit('change')//這裏傳入的是你要調用的函數的名字

2.actions通過mutation來改變狀態,而不是直接改變狀態

actions內部可以有異步操作,而mutations不行

var store = new Vuex.Store({
    state:{
        name:"胡志武"
    },
    mutations:{
    //這裏傳入的是state	
		change(state){
			state.name="志武胡"
		}
	},
    actions:{
        //這裏傳入的是上下文
         actionChange(context){
             context.commit('change')
          }
    }
)

//如何調用
this.$store.dispatch('actionChange')

3.getters 獲取狀態的同時,進行判斷

var store = new Vuex.Store({
    state:{
        name:"胡志武"
    },
    mutations:{
    //這裏傳入的是state	
		change(state){
			state.name="志武胡"
		}
	},
    actions:{
        //這裏傳入的是上下文
         actionChange(context){
             context.commit('change')
          }
    },
    getters:{
        getName(state){
            return state.name===''?'胡志武':state.name
        }        
    
//調用
this.$store.getters.getName
)

4.Vuex的模塊裏的狀態

new Vuex.Store({
    modules:{
        user:{
            state:{
                admin:'胡志武'
            },
            mutations:{},
            ...
        }
    }
})
// 如何訪問
    this.$store.state.user.admin

參考文章:
https://www.cnblogs.com/wisewrong/category/933810.html
https://juejin.im/post/5ce810786fb9a07ea9444af1
https://juejin.im/entry/597ab13d5188253e0a62efcb
https://segmentfault.com/a/1190000012116116#articleHeader12
https://www.cnblogs.com/keepfool/p/5690366.html
https://juejin.im/post/5a0ea4ec6fb9a0450407725c

官方參考資料:
axios:https://cn.vuejs.org/v2/cookbook/using-axios-to-consume-apis.html#%E5%9F%BA%E6%9C%AC%E7%9A%84%E7%A4%BA%E4%BE%8B
Vue-router:https://router.vuejs.org/zh/guide/#html
Vuex:https://vuex.vuejs.org/zh/

3.axios請求攔截和響應攔截

import axios from 'axios'
import { Message, Loading } from 'element-ui';
import router from './router'

//http.js對axios進行封裝

let loading        //定義loading變量

function startLoading() {    //使用Element loading-start 方法
    loading = Loading.service({
        lock: true,
        text: '加載中...',
        background: 'rgba(0, 0, 0, 0.7)'
    })
}
function endLoading() {    //使用Element loading-close 方法
    loading.close()
}

// 請求攔截  設置統一header
axios.interceptors.request.use(config => {
    // 加載
    startLoading()
    if (localStorage.eleToken)
        config.headers.Authorization = localStorage.eleToken
    return config
}, error => {
    return Promise.reject(error)
})

// 響應攔截  401 token過期處理
axios.interceptors.response.use(response => {
    endLoading()
    return response
}, error => {
    // 錯誤提醒
    endLoading()
    Message.error(error.response.data)

    const { status } = error.response
    if (status == 401) {
        Message.error('token值無效,請重新登錄')
        // 清除token
        localStorage.removeItem('eleToken')

        // 頁面跳轉
        router.push('/login')
    }

    return Promise.reject(error)
})

export default axios
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章