Vue(二)進階

Vue腳手架:

 vue-cli:

全局安裝:javascript

npm install  -g  vue-cli

查看版本:html

vue -V

初始化腳手架:vue

vue init webpack + 項目的名字

運行項目:java

npm run dev

打包項目:webpack

npm run build

文件及文件夾的信息:

開發依賴:  開發編譯打包須要的依賴,打包以後就不要了 
生產依賴:  打包先後都須要的依賴

Vue-router:

下載安裝:
npm install vue-router

在router文件夾下新建js文件:ios

import VueRouter from 'vue-router'//引入路由模塊
       import Vue from 'vue'
       Vue.use(VueRouter)//依賴模塊
       let router=new VueRouter({
       	routes:[
			{path:'路徑(加斜槓訪問)',name:"名字(直接訪問)",component:'註冊組件(跳轉的位置)',chidern:[]子路由}
			{path:'/',redirect:"/home"},//路由的重定向 若是hash 爲'/' 指向到 /home
       	]
       })
       export default router

經過<router-link to='/path'>標籤來切換組件web

經過<router-view>標籤顯示ajax

keep-alive:在component組件、router-view外面包裹上keep-alive的話,就會對組件進行緩存,當切換回來的時候,組件會當即渲染,理論來講,切換組件的時候其實會把上一個組件銷燬,使用了keep-alive則不會(就是組件一直存在於緩存中)vue-router

include匹配到的組件會被緩存,exclude匹配到的不會被緩存vuex

值能夠爲逗號隔開的字符串include = ‘a,b’;正則:include = ‘/a|b/’;數組:include=[‘a’,’b’]

多級路由:

const routes = [
  {path:'/main',component:AppMain},
  {path:'/news',component:AppNews,children:[//children是子目錄
    {path:'inside',component:AppNewsInside},
    {path:'outside',component:AppNewsOutside}
  ]},
]

默認路由:

{path:'',component:Main}//將默認路徑設置成Main

動態路由:

{path:'/user/:id',component:User}//id爲傳的值

命名路由:

直接用name : main在hash中寫name就能夠路由

路由跳轉:

router.push = router-link:to router.replace = router-link:to.replace router.go() = window.history.go

 路由鉤子:

全局路由鉤子:

router.beforeEach((to, from, next) => {
    //會在任意路由跳轉前執行,next必定要記着執行,否則路由不能跳轉了
  console.log('beforeEach')
  console.log(to,from)
  //
  next()
})
//
router.afterEach((to, from) => {
    //會在任意路由跳轉後執行
  console.log('afterEach')
})

局部路由:

routes: [
    {
      path: '/foo',
      component: Foo,
      beforeEnter: (to, from, next) => {
        // ...
      }
    }
  ]

組件內的路由鉤子:

beforeRouteEnter (to, from, next) //confirm 前調用
beforeRouteUpdate (to, from, next) //在當前路由改變調用
beforeRouteLeave (to, from, next)//導航離開該組件的對應路由時調用

生命週期:

beforeCreate:

建立組件以前,沒有組件,沒有元素,沒有事件,沒有生命週期

created:

建立組件結束,有數據,沒有元素

beforeMount:

掛載以前,有數據,沒有元素

mounted:

掛載完成,有元素,有數據

beforeUpdate:(在mounted後執行)

用於監聽數據變化

updated:

用於監聽數據變化

beforeDestroy:

銷燬實例,元素數據還在

destroyed:

銷燬實例

Vue中的ajax:

axios:

載入:npm install axios

在main.js中

import Axios from 'axios';//引入
Vue.prototype.$axios = Axios;//將Axios附着在Vue,以供全局調用
Axios.defaults.baseURL = 'http://localhost:1024';//設置默認接口地址

而後在須要請求的組件中:

this.$axios
        .post("hash",data)//hash是接口地址,不須要加主機地址(http://localhost/index直接寫/index)data是傳輸的對象
        .then(res => {//返回值
          if (res.data.err == 0) {
           console.log(res)
          }
        })
        .catch(err => {
          console.log(err);
        });

axios攔截器:

請求攔截:

axios.interceptors.request.use(function (config) {//發送以前進行過濾
    return config;
  }, function (error) {
    return Promise.reject(error);
  });

響應攔截:

axios.interceptors.response.use(function (response) {//請求到數據後進行過濾
    return response;
  }, function (error) {
    return Promise.reject(error);
  });

Vuex:

做用:多個組件共享狀態及數據

安裝:npm install vuex

配置:在src中新建store文件夾:在裏面新建js文件

import Vue from 'vue'
import Vuex from 'vuex'//引入Vuex
Vue.use(Vuex);
import login from './login/index'
const store = new Vuex.Store({
  modules: {
    login: login,
  }
})
export default store;//拋出vuex實例

在src中新建的store文件夾中新建另外一個文件夾:裏面有5個js文件

大體示範一下里面的內容(部分購物車內容,大概看一下就好):

index.js

import state from './state';
import mutations from './mutations';
import getters from './getters';
import actions from './actions';
let store = {
  state,
  mutations,
  getters,
  actions
};

export default store;

state.js

export default {
  carObj: [],
}

getters.js

export default {
  // 派生屬性
  all(state) {
    var price = 0;
    var sum = 0;
    var seleceAll = true;
    for (let i = 0; i < state.carObj.length; i++) {
      if (state.carObj[i].sel) {
        price += state.carObj[i].price * state.carObj[i].num;
        sum += state.carObj[i].num;
      }
      seleceAll *= state.carObj[i].sel;
    }
    return {
      price: price,
      sum: sum,
      seleceAll: seleceAll
    }
  }
}

mutations.js:

export default {
  //只作狀態值得修改 不作任何邏輯操做
  addTo(state, carObj) {
    state.carObj = carObj
  }
}

actions.js:

export default {
  // // 異步處理邏輯操做
  initCar({
    commit
  }) {
    let carlist = localStorage.carlist ? JSON.parse(localStorage.carlist) : [];
    commit('addTo', carlist)
  }
}

主要流程:(官網的)

初步理解就是:經過actions的函數改變states(數據),渲染到全部綁定的頁面,頁面再次調用actions(函數),再次修改

深層理解:組件觸發actions傳遞數據(拋發),觸發mutations修改狀態值,修改state的值,渲染到頁面

輔助工具:

import { mapState,mapGetters,mapMutations,mapActions } from 'vuex'

 引入輔助工具使組件能夠設置或獲取到函數及數據

this.$store//獲取到store

mapStates:

computed: {
  // 使用對象展開運算符將此對象混入到外部對象中
  ...mapState({
        //state中的變量名
  })
}

mapGetters:

computed: {
  // 使用對象展開運算符將 getter 混入 computed 對象中
    ...mapGetters([
      'doneTodosCount',
      'anotherGetter'
    ])
  }

 mapMutations:

methods: {
    ...mapMutations([
      'increment', // 將 `this.increment()` 映射爲 `this.$store.commit('increment')`
      // `mapMutations` 也支持載荷:
      'incrementBy' // 將 `this.incrementBy(amount)` 映射爲 `this.$store.commit('incrementBy', amount)`
    ])
  }

mapActions:

methods: {
    ...mapActions([
      'increment', // 將 `this.increment()` 映射爲 `this.$store.dispatch('increment')`
      // `mapActions` 也支持載荷:
      'incrementBy' // 將 `this.incrementBy(amount)` 映射爲 `this.$store.dispatch('incrementBy', amount)`
    ])
  }
相關文章
相關標籤/搜索