vue 使用总结

vue 使用总结

本文配套项目地址.javascript

给 vue 全局挂载方法

全局挂载 axios

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

Vue.prototype.$axios = Axios;java

在启动入口增长 axio 后,组件中使用 axio 不须要再进行 import 操做.例如:webpack

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

挂载一个自定义的方法

  1. 定义须要挂载的方法ios

    // 请求阿里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. 在入口文件中引入 funcgit

    Vue.use(func);

    而后就能够在组件中使用this.$OSSTail()啦.github

axios 全局设置

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

设置基本参数

在一个项目中请求地址一般都有些统一的配置,将这些配置提取出来能够增长代码的复用性.vue-router

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

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

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

/* 请求拦截器 */
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
      }
    }
  }
};
相关文章
相关标签/搜索