使用Vuex、Vue路由、axios的經驗彙總

博客說明:

文章所涉及的資料來自互聯網整理和個人總結,意在於個人學習和經驗彙總,如有什麼地方侵權,請聯繫本人刪除;如有什麼地方存在異議,請在評論區或私信指出,謝謝!


一、Vuex

Vuex 是一個狀態管理工具 (store是唯一的;存數據;取數據;改數據)

  1. 使用步驟

① 安裝

npm i vuex --save

② 導入

import Vuex from 'vuex'

③ 使用

Vue.use(Vuex)

④ 實例化

例:

var store = new Vuex.Store({
     state:{
		n:666
    },
    mutations:{
		XXX(state,payload){
			state.n+=payload
	   }
    }
  })

⑤ 在實例中註冊

new Vue({
	...
	 store,
	...
})
  1. mutations(同步改變數據)
mutaions:{
	XXX(state,payload){
		state.n+=payload
	 }
 }

注:

this.$store.commit("mutations裏的方法名",參數)
  1. getters(倉庫裏的計算屬性)
getters:{  
    屬性(state){
        return 計算屬性的值
     }
 }
  1. actions(異步方法)
異步方法(context,payload){
    異步成功的回調裏   context.commit("mutaions裏的同步方法",傳參)
 }

注:

this.$store.dispatch("actions裏的異步方法","參數");
  1. modules

① 分模塊

var 模塊={
   state:{},mutations:{},actions:{}
}

new Vuex.Store({
   modules:{
    模塊的名字:引入的模塊,....
   }
})

// state 有區別   this.$store.state.模塊名.變量
// 其他的mutations actions,getters裏的方法調用和之前一樣

② 分模塊後的重名問題

如果getters 重名會報錯;
mutaions方法重名,各個模塊的裏的這個方法都會調用;
actions方法重名,各個模塊裏的方法都會調用;

namespaced: true, 命名空間

啓用命名空間後,mutations或actions 方法名 變爲 模塊名/方法名

  1. 四個輔助函數
...mapState("模塊名","變量"){{模塊名.變量}}

...mapGetters({
 變量: 模塊名/變量
})
...mapMutations({
    方法名: 模塊名/mutaions裏的方法名
})
...mapActions({
   方法名:模塊名/actions裏的方法名
})

二、Vue路由

前端路由:根據不同的url切換組件
後端路由:根據不同的請求返還不同的內容

  1. 安裝
npm i vue-router —save
  1. 使用路由的步驟

① 引入vuerouter

import VueRouter from 'vue-router'

② 使用VueRouter

Vue.use(VueRouter) 

③ 實例化

var router = new VueRouter({ 
   routes:[
   		{ 
   			path:'xxx',
   			component:Com
   		}....
   ]
})

new Vue({
   ...
      router
   ...
})

⑤ App.vue中使用如下代碼

<router-view />
<router-link to="/one">xxx</router-link>
  1. 路由的兩種模式
    history 模式
    hash 模式
  2. 路由的重定向:redirect
  3. 命名路由:name
  4. 別名:alias
  5. 命名視圖:
<router-view name="xxx" />
  {

  	path:xxx,

  	components:{

  		default:組件,  

  		router-view的名字:渲染組件;

  	}
  }
  1. 當前路由樣式

router-link-exact-active

router-link-active (子路由有樣式,父路由也有)

  1. 錯誤頁面
{
   path:"**",
   component:NotFound,
}
  1. 路由傳參

①傳遞少量參數

{
  path:'/xxx/:p',
  component:Xxx
}
this.$route.paramms.p(參數變量)

②監控參數變化

 watch:{
     $route:{
         handler(n){  n 相當於this.$route
                n.meta.flag 可以拿到路由的元數據
         },
     	immediate:true
   }
}

③ 編程式導航(適合傳多個參數)

this.$router.push({name:'xxx',params:{key:value....},query:{key:vaule...}})
// 跳轉到名字叫 xxx路由對象,帶過去params對象裏的參數,並且把query裏的健值對放到 ?後面
// 拿到query 傳的值  this.$route.query.變量
  1. 路由過渡效果
v-enter v-enter-active v-enter-to v-leave v-leave-active v-leave-to

<transtion mode="out-in"> out-in 是表示先退場再進場 <router-view /> </transtion>

在public/index.html 中使用從BootCDN引過來的
animate.css即可

<link href="https://cdn.bootcdn.net/ajax/libs/animate.css/3.7.2/animate.css" rel="stylesheet">
<transition mode="out-in" enter-active-class="animated slideInLeft" 
leave-active-class="animated slideOutLeft">
  1. 導航守衛
// 全局守衛
      beforeEach(to,from,next)  // to:就是切換到路由的對象; from:當前路由的對象 ;next:跳轉
      afterEach(to,from)
// 路由獨享的守衛
       beforeEnter
// 組件內的守衛
       // 路由進入之前
       beforeRouteEnter( 比beforeCreate要早)
       next((vm)=>{
         	vm.組件裏的數據
       })
       //路由更新之前  
       beforeRouteUpdate
       //路由離開之前
       beforeRouteLeave

三、axios

  1. 安裝
npm i axios --save
  1. 使用
axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
axios.post('/user', {
  firstName: 'Fred',
  lastName: 'Flintstone'
})
.then(function (response) {
  console.log(response);
})
.catch(function (error) {
  console.log(error);
});
axios({
method: 'post',
url: '/user/12345',
data: {
 firstName: 'Fred',
 lastName: 'Flintstone'
}
}).then(function(res) {
 console.log(res)
 });
  1. 獲取數據後異步傳值
​ v-if 可以保證數據返回後再渲染組件
  1. axios的重複引用問題

可以在入口文件 main.js使用命令

import axios from 'axios';
Vue.prototype.$axios=axios

把請求的所有方法,都封裝起來,需要請求時調用

  1. 請求中的跨域問題

1)後端:cors

res.setHeader("Access-Control-Allow-Origin","*");

2)前端:正向代理

創建vue.config.js文件

module.exports ={
devServer:{  //開發服務器設置
   proxy:{   //代理
     "/hd":{
         "target":"http://localhost:3000",
         "changeOrigin":true,
         "pathRewrite":{
             "^/hd":""
         }
     }
   }
}
}
  1. $nextTick
this.$nextTick(callback);

nextTick 延遲執行回調函數,直到dom就緒


【附】Vue中文教程

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