vue 使用总结

vue 使用总结

本文配套项目地址.

给 vue 全局挂载方法

全局挂载 axios

由于在 javascript 中存在以下等式 func.prototype === new func().__proto__,且 vue 组件中的 this 为 Vue 的实例,故可以使用以下方法为 Vue 添加方法.

Vue.prototype.$axios = Axios;

在启动入口增加 axio 后,组件中使用 axio 不需要再进行 import 操作.例如:

this.$axios
    .get("product/region")
    .then(this.$resp(res => {}))
    .catch(err => console.log(err));
},

挂载一个自定义的方法

  1. 定义需要挂载的方法

    // 请求阿里oss图片的配置参数
    func.install = function(Vue, options) {
    Vue.prototype.$OSSTail = function(url) {
        if (!url) {
        return;
        }
        return url.split("?")[0] + "?x-oss-process=image/resize,w_600";
    };
    };
    
  2. 在入口文件中引入 func

    Vue.use(func);
    

    然后就可以在组件中使用this.$OSSTail()啦.

axios 全局设置

axios 用于发送 http 请求,返回 promise.

设置基本参数

在一个项目中请求地址通常都有些统一的配置,将这些配置提取出来可以增加代码的复用性.

Axios.defaults.baseURL = "/api/v1.0/";
Axios.defaults.headers.post["Content-Type"] = "application/json";
...

添加请求钩子统一处理请求

一般前后端交互需要进行身份认证,这里以 JWT 为例,通过设置请求钩子为每个请求添加一个 header. 然后监控每个响应,当有 token 返回时,将 token 存入 localStorage.

/* 请求拦截器 */
Axios.interceptors.request.use(
  function(config) {
    // 每次请求时会从localStorage中获取token
    let token = Storage.localGet("token");
    if (token) {
      // 把token加入到默认请求参数中
      token = token.replace(/'|"/g, "");
      config.headers.common["Authorization"] = token;
    }
    return config;
  },
  function(error) {
    return error;
  }
);

/* 响应拦截器 */
Axios.interceptors.response.use(
  function(response) {
    if (response.data.code === -1) {
      // 删除已经失效或过期的token(不删除也可以,因为登录后覆盖)
      Storage.localRemove("token");
      // 设置登陆后跳转页面
      store.commit("set_jump", router.currentRoute.name);
      // 跳转到登录页
      router.replace({
        path: "/login"
      });
    } else if (response.data.token) {
      // 判断token是否存在,如果存在说明需要更新token
      Storage.localSet("token", response.data.token);
    }
    return response;
  },
  function(error) {
    return error;
  }
);

vue-router

使用

  1. 实例化 Router 对象

    export default new Router({
      routes: [
        {
          path: "/",
          name: "index",
          component: () => import("./views/Index.vue"),
          meta: { keepAlive: true }
        }
      ]
    });
    
  2. 入口处挂载

    new Vue({
        router,
        store,
        render: h => h(App)
    }).$mount("#app");
    

对路由进行缓存

  1. 路由中 meta 添加自定义标识,如上例, { keepAlive: true }

  2. 根据条件使用 keepalive 组件进行缓存

    以下示例表示当路由 meta 中 keepAlive 项为 true 时则进行缓存,否则正常处理.

    <template>
    <div id="app">
        <keep-alive>
        <router-view v-if="$route.meta.keepAlive"></router-view>
        </keep-alive>
        <router-view v-if="!$route.meta.keepAlive"></router-view>
    </div>
    </template>
    

vuex 的使用

何时使用

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。当不同组件中需要共享状态,一般会用到它. 例如本例中登录后跳转地址.

使用

  1. 全局一个 store 对象

    export default new Vuex.Store({
         state: {
             jump: "index",  // 登陆后跳转路由
         },
    
         // set state
         mutations: {
             set_jump(state, page) {
                 state.jump = page
             }
         },
    
         // Action 提交的是 mutation,而不是直接变更状态。
         // Action 可以包含任意异步操作。
         actions: {
    
         }
    })
    
  2. 调用

    // 更改状态
    this.$store.commit("set_jump", router.currentRoute.name);
    // 获取状态
    this.$store.state.jump;
    

对组件进行缓存

<keep-alive>
    <loading></loading>
</keep-laive>

keep-alive 是 Vue 提供的一个抽象组件,用来对组件进行缓存,从而节省性能,由于是一个抽象组件,所以在页面渲染完毕后不会被渲染成一个 DOM 元素.
当组件在 keep-alive 内被切换时组件的 activateddeactivated 这两个生命周期钩子函数会被执行.

通过组件名字定义缓存规则

<keep-alive include="bookLists,bookLists">
      <router-view></router-view>
</keep-alive>
<keep-alive exclude="indexLists">
      <router-view></router-view>
</keep-alive>

通过路由属性定义缓存规则

见 vue-router 一节.

父子组件通讯

父组件向子组件传值

  1. 子组件定义 props:list 项,props 中所有的项目都会被转化为组件的属性,可以用 this 调用.例如:

    export default {
    props: ["product_type", "region_type"],
    methods: {
        get_region() {
          return this.product_type;
        }
      }
    }
    
  2. 父组件定义 props 中对应的属性

    <Product product_type="微留学" region_type="国内" />
    

子组件向父组件传值

本例中导航栏是父组件,导航栏中的每一项是一个子组件.

  1. 父组件中调用子组件时传入一个事件

    <template>
      <Item
        :txt="item.txt"
        @change="getVal"  // 自定义的事件
      />
    <template>
    
  2. 子组件触发事件

    this.$emit("change", params);
    

对插槽的理解

父组件调用子组件时可以传入一些基本类型的值,但是无法传入一个/一组组件作为参数;插槽的作用就是传入子组件一个/一组组件作为参数.

  • 位置插槽

  • 命名插槽

  • 作用域插槽

vue-cli3 设置代理

vue-cli3隐藏了webpack的配置.如需增加自定义配置项,需要在根目录(与package.json同级)新增配置文件vue.config.js.

具体配置见 全局-cli-配置.

  • 代理配置如下
module.exports = {
  devServer: {
    proxy: {
      "/api/v1.0": {
        target: "http://glocalschool.killf.info",
        ws: true,
        changeOrigin: true
      }
    }
  }
};
posted @ 2019-07-13 16:10  Aloe_n  阅读(157)  评论(0编辑  收藏  举报