一路繁花似锦绣前程
失败的越多,成功才越有价值

导航

 

main.js

import Vue from 'vue'
import App from './App'
import router from './router'
import store from './vuex'
import Axios from 'axios'

Vue.prototype.$axios=Axios

Axios.defaults.baseURL="http://www.wwtliu.com"

Vue.config.productionTip = false

new Vue({
    el: '#app',
    router,
    store,
    components: {App},
    template: '<App/>'
})

一、router

import Vue from 'vue'
import Router from 'vue-router'
import all from '@/components/all'

Vue.use(Router)

const router = new Router({
  mode: "history",//nginx需配置:server{location / {try_files $uri $uri/ /index.html;}}
  routes: [
    {
      path: '/',
      redirect: "/all"
    },
    {
      path: '/all',
      component: all
    },
    {
      path: '/all/:data',
      component: all
    },
    {
      path: '/all',
      component: all,
      children: [
        {
          path: '/all/first',
          component: first,
        },
        {
          path: 'second',
          component: second,
        }
      ]
    }
  ]
})

export default router;
<router-link to="/all" tag="li">全部</router-link>

<router-view/>
this.$router.push({name:'',path:'',query:{data:''},params:{data:''}})

this.$route.query.data
this.$route.params.data

路由守卫:

beforeRouteEnter(to,from,next){
    if(false){
        next();
    }else{
        next("/login");
    }
}

router.beforeEach((to,from,next)=>{
    if(to.path=="/info" && false){
        next()
    }else{
        next("/login")
    }
})

路由监听:

watch: {
  "$route.path": function () {
  }
},

二、vuex

import Vue from "vue"
import Vuex from "vuex"

Vue.use(Vuex)

const store = new Vuex.Store({
    state: {
        list:[]
    },
    mutations: {
        add(state,arg){
            state.list.push(arg);
        }
    },
    getters:{
        activelist(state){
            return state.list.filter(item=>item.tasksty)
        }
    },
    actions:{
        //异步处理
        saveDataAction(arg_store,data){
            arg_store.commit('add',data);
        }
    }
})

export default store;
this.$store.dispatch("saveDataAction",'data_data_data');
<input type="text" placeholder="你打算做什么?"  @keyup.enter="modelvalue">

methods:{
    modelvalue(ev){
        this.$store.commit("add",{taskval:ev.target.value,tasksty:false});
    }
}
<li v-for="li in list"></li>
<li v-for="li in activelist"></li>

import {mapState,mapGetters} from "vuex"
computed:{ 
    ...mapState(["list"]),
    ...mapGetters(["activelist"])
}

vuex持久化

1、安装
  npm i -S vuex-persistedstate
2、配置
  import persistedState from 'vuex-persistedstate'
  const store = new Vuex.Store({
    plugins: [
      persistedState({
        storage: window.sessionStorage,
        // keep-alive需取消持久化,否则会报错
        // vuex动态模块需取消持久化,否则会报警告
        reducer(state) {
          const processState = { ...state }; // state:属性不能删
          delete processState.tagsView;
          return processState; // processState:持久化的对象
        }
      })
    ]
  })

vuex命名空间

import Vue from "vue"
import Vuex from "vuex"

Vue.use(Vuex)

let storemodule = {
  // namespaced为false(默认),state依然要加模块名
  namespaced: true,
  state: {
    storemodulestate: ""
  },
  mutations: {
    setStoremodulestate(state, arg) {
      state.storemodulestate = arg
    }
  },
  getters: {
    getStoremodulestate(state) {
      return state.storemodulestate
    }
  }
}

export default new Vuex.Store({
  modules: {storemodule}
})
<template>
    <div>
    </div>
</template>

<script>
    import {mapGetters} from "vuex"

    export default {
        name: "index",
        computed: {
            ...mapGetters({
                storemodulestate: "storemodule/getStoremodulestate",
                modulestate: "storemodule/getStoremodulestate"
            })
        },
        mounted() {
            console.log(this.storemodulestate)
            this.$store.commit("storemodule/setStoremodulestate", "setStoremodulestate")
            console.log(this.modulestate)
        }
    }
</script>

<style scoped>

</style>

三、axios

this.$axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
}, {
    headers: {
        'token': ''
    },
    responseType: 'blob'
}).then(function (response) {
    console.log(response);
    /**
     * 1、后端response.setConentType和response.setCharacterEncoding,
     *   前端参数2可以省略
     */
    let blob = new Blob([response.data], {type: "application/vnd.ms-excel,charset=utf-8"});
    let link = window.URL.createObjectURL(blob);
    let element = document.createElement("a");
    element.href = link;
    /**
     * 2、后端String fileName = URLEncoder.encode(【文件名】, "UTF-8");
     *   后端response.setHeader("Content-disposition", "attachment;filename=" + fileName),
     *   前端文件名可从响应头获取
     *     - const fileName = decodeURI(response.headers.filename)
     */
    element.download = "文件名.xlsx";
    document.body.appendChild(element);
    element.click();
    window.URL.revokeObjectURL(link);
    document.body.removeChild(element);
}).catch(function (error) {
    console.log(error);
});

this.$axios.get('/user', {
    headers: {
        'token': ''
    },
    responseType: 'blob',
    params:{
        firstName: 'Fred',
        lastName: 'Flintstone'
    }
}).then(function (response) {
    console.log(response);
}).catch(function (error) {
    console.log(error);
});
axios.interceptors.request.use(req => {
  /**
   * 一、取消请求案例:路由跳转取消上一页所有请求
   * if (window.axiosCancelTokens) {
   *   window.axiosCancelTokens.forEach(cancel => {
   *     cancel();
   *   });
   *   window.axiosCancelTokens = [];
   * }
   */
  req.cancelToken = new axios.CancelToken(cancel => {
    if (window.axiosCancelTokens) {
      window.axiosCancelTokens.push(cancel);
    } else {
      window.axiosCancelTokens = [cancel];
    }
  });
  return req;
}, err => {
  return Promise.reject(err);
})

axios.interceptors.response.use(res => {
  return res;
}, err => {
  return Promise.reject(err);
})
// 表单提交方式
const formData = new FormData()
// 参数2:只能是二进制流或字符串
formData.append('firstName', 'Fred')
formData.append('lastName', 'Flintstone')
this.$axios.post('/user', formData, {
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    }
}).then(function (response) {
    console.log(response);
}).catch(function (error) {
    console.log(error);
});
Axios({
  // 允许处理上传的进度事件
  onUploadProgress: function ({loaded, total, progress, bytes, estimated, rate, upload = true}) {
  },
  // 允许处理下载的进度事件(后端请求头需加上Content-Length参数)
  onDownloadProgress: function ({loaded, total, progress, bytes, estimated, rate, download = true}) {
  },
})

 

posted on 2020-02-27 23:00  一路繁花似锦绣前程  阅读(331)  评论(0编辑  收藏  举报