第三方插件可以增强vue,帮助我们更好的开发项目,如axios, vuex, vue-router,elementui等

我们可以自定义插件,步骤如下:

  1. 在vue项目下的src文件夹下创建plugins文件夹,创建一个index.js文件
  2. 在index.js中定义插件
    import Vue from 'vue'
    export default {
        install(a) {
            console.log(a)
            // 写代码,加入混入
            Vue.mixin({
                methods: {
                    handleShowName() {
                        alert(this.name)
                    }
                }
            })
        
    
        }
    }

  3. 使用插件 在main.js中添加如下代码
    import plugins from './plugins'
    Vue.use(plugins) // 自动调用插件内的install,完成对Vue的强化

     

1.axios组件

安装:

npm install -S axios

 使用:

发送get请求

<script>
// 导入axios
import axios from 'axios'
// 使用axios
axios.get('http://127.0.0.1:8000/user/').then(res=>{
  // 正确返回数据操作
  console.log(res.data)
}).catch(error=>{
// 发送失败处理
})
</script>

发送post请求,并携带参数

import axios from 'axios'
axios.post('http://127.0.0.1:8000/user/', {'username':'kunmzhao', 'password':'123'}).then(res=>{

}).catch(error=>{

})

发送post请求。携带参数,头部携带token

 

详细使用:


  1  1 // 发起一个post请求
  2   2 axios({
  3   3   method: 'post',
  4   4   url: '/user/12345',
  5   5   data: {
  6   6     firstName: 'Fred',
  7   7     lastName: 'Flintstone'
  8   8   }
  9   9 });
 10  10 
 11  11 
 12  12 
 13  13 {
 14  14   // url 是用于请求的服务器 URL
 15  15   url: '/user',
 16  16 
 17  17   // method 是创建请求时使用的方法
 18  18   method: 'get', // 默认值
 19  19 
 20  20   // baseURL 将自动加在 url 前面,除非 url 是一个绝对 URL。
 21  21   // 它可以通过设置一个 baseURL 便于为 axios 实例的方法传递相对 URL
 22  22   baseURL: 'https://some-domain.com/api/',
 23  23 
 24  24   // transformRequest 允许在向服务器发送前,修改请求数据
 25  25   // 它只能用于 'PUT', 'POST' 和 'PATCH' 这几个请求方法
 26  26   // 数组中最后一个函数必须返回一个字符串, 一个Buffer实例,ArrayBuffer,FormData,或 Stream
 27  27   // 你可以修改请求头。
 28  28   transformRequest: [function (data, headers) {
 29  29     // 对发送的 data 进行任意转换处理
 30  30 
 31  31     return data;
 32  32   }],
 33  33 
 34  34   // transformResponse 在传递给 then/catch 前,允许修改响应数据
 35  35   transformResponse: [function (data) {
 36  36     // 对接收的 data 进行任意转换处理
 37  37 
 38  38     return data;
 39  39   }],
 40  40 
 41  41   // 自定义请求头
 42  42   headers: {'X-Requested-With': 'XMLHttpRequest'},
 43  43 
 44  44   // params 是与请求一起发送的 URL 参数
 45  45   // 必须是一个简单对象或 URLSearchParams 对象
 46  46   params: {
 47  47     ID: 12345
 48  48   },
 49  49 
 50  50   // paramsSerializer是可选方法,主要用于序列化params
 51  51   // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
 52  52   paramsSerializer: function (params) {
 53  53     return Qs.stringify(params, {arrayFormat: 'brackets'})
 54  54   },
 55  55 
 56  56   // data是作为请求体被发送的数据
 57  57   // 仅适用 'PUT', 'POST', 'DELETE 和 'PATCH' 请求方法
 58  58   // 在没有设置 `transformRequest` 时,则必须是以下类型之一:
 59  59   // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
 60  60   // - 浏览器专属: FormData, File, Blob
 61  61   // - Node 专属: Stream, Buffer
 62  62   data: {
 63  63     firstName: 'Fred'
 64  64   },
 65  65 
 66  66   // 发送请求体数据的可选语法
 67  67   // 请求方式 post
 68  68   // 只有 value 会被发送,key 则不会
 69  69   data: 'Country=Brasil&City=Belo Horizonte',
 70  70 
 71  71   // `timeout` 指定请求超时的毫秒数。
 72  72   // 如果请求时间超过 `timeout` 的值,则请求会被中断
 73  73   timeout: 1000, // 默认值是 `0` (永不超时)
 74  74 
 75  75   // `withCredentials` 表示跨域请求时是否需要使用凭证
 76  76   withCredentials: false, // default
 77  77 
 78  78   // `adapter` 允许自定义处理请求,这使测试更加容易。
 79  79   // 返回一个 promise 并提供一个有效的响应 (参见 lib/adapters/README.md)。
 80  80   adapter: function (config) {
 81  81     /* ... */
 82  82   },
 83  83 
 84  84   // `auth` HTTP Basic Auth
 85  85   auth: {
 86  86     username: 'janedoe',
 87  87     password: 's00pers3cret'
 88  88   },
 89  89 
 90  90   // `responseType` 表示浏览器将要响应的数据类型
 91  91   // 选项包括: 'arraybuffer', 'document', 'json', 'text', 'stream'
 92  92   // 浏览器专属:'blob'
 93  93   responseType: 'json', // 默认值
 94  94 
 95  95   // `responseEncoding` 表示用于解码响应的编码 (Node.js 专属)
 96  96   // 注意:忽略 `responseType` 的值为 'stream',或者是客户端请求
 97  97   // Note: Ignored for `responseType` of 'stream' or client-side requests
 98  98   responseEncoding: 'utf8', // 默认值
 99  99 
100 100   // `xsrfCookieName` 是 xsrf token 的值,被用作 cookie 的名称
101 101   xsrfCookieName: 'XSRF-TOKEN', // 默认值
102 102 
103 103   // `xsrfHeaderName` 是带有 xsrf token 值的http 请求头名称
104 104   xsrfHeaderName: 'X-XSRF-TOKEN', // 默认值
105 105 
106 106   // `onUploadProgress` 允许为上传处理进度事件
107 107   // 浏览器专属
108 108   onUploadProgress: function (progressEvent) {
109 109     // 处理原生进度事件
110 110   },
111 111 
112 112   // `onDownloadProgress` 允许为下载处理进度事件
113 113   // 浏览器专属
114 114   onDownloadProgress: function (progressEvent) {
115 115     // 处理原生进度事件
116 116   },
117 117 
118 118   // `maxContentLength` 定义了node.js中允许的HTTP响应内容的最大字节数
119 119   maxContentLength: 2000,
120 120 
121 121   // `maxBodyLength`(仅Node)定义允许的http请求内容的最大字节数
122 122   maxBodyLength: 2000,
123 123 
124 124   // `validateStatus` 定义了对于给定的 HTTP状态码是 resolve 还是 reject promise。
125 125   // 如果 `validateStatus` 返回 `true` (或者设置为 `null` 或 `undefined`),
126 126   // 则promise 将会 resolved,否则是 rejected。
127 127   validateStatus: function (status) {
128 128     return status >= 200 && status < 300; // 默认值
129 129   },
130 130 
131 131   // `maxRedirects` 定义了在node.js中要遵循的最大重定向数。
132 132   // 如果设置为0,则不会进行重定向
133 133   maxRedirects: 5, // 默认值
134 134 
135 135   // `socketPath` 定义了在node.js中使用的UNIX套接字。
136 136   // e.g. '/var/run/docker.sock' 发送请求到 docker 守护进程。
137 137   // 只能指定 `socketPath` 或 `proxy` 。
138 138   // 若都指定,这使用 `socketPath` 。
139 139   socketPath: null, // default
140 140 
141 141   // `httpAgent` and `httpsAgent` define a custom agent to be used when performing http
142 142   // and https requests, respectively, in node.js. This allows options to be added like
143 143   // `keepAlive` that are not enabled by default.
144 144   httpAgent: new http.Agent({ keepAlive: true }),
145 145   httpsAgent: new https.Agent({ keepAlive: true }),
146 146 
147 147   // `proxy` 定义了代理服务器的主机名,端口和协议。
148 148   // 您可以使用常规的`http_proxy` 和 `https_proxy` 环境变量。
149 149   // 使用 `false` 可以禁用代理功能,同时环境变量也会被忽略。
150 150   // `auth`表示应使用HTTP Basic auth连接到代理,并且提供凭据。
151 151   // 这将设置一个 `Proxy-Authorization` 请求头,它会覆盖 `headers` 中已存在的自定义 `Proxy-Authorization` 请求头。
152 152   // 如果代理服务器使用 HTTPS,则必须设置 protocol 为`https`
153 153   proxy: {
154 154     protocol: 'https',
155 155     host: '127.0.0.1',
156 156     port: 9000,
157 157     auth: {
158 158       username: 'mikeymike',
159 159       password: 'rapunz3l'
160 160     }
161 161   },
162 162 
163 163   // see https://axios-http.com/zh/docs/cancellation
164 164   cancelToken: new CancelToken(function (cancel) {
165 165   }),
166 166 
167 167   // `decompress` indicates whether or not the response body should be decompressed
168 168   // automatically. If set to `true` will also remove the 'content-encoding' header
169 169   // from the responses objects of all decompressed responses
170 170   // - Node only (XHR cannot turn off decompression)
171 171   decompress: true // 默认值
172 172 
173 173 }

View Code

 

2.elementui的使用

作用:帮我们美化页面

支持vue2版本的:https://element.eleme.cn/#/zh-CN/component/installation

支持vue3把版本的:https://element-plus.gitee.io/zh-CN/guide/quickstart.html

2.1 安装

2.1.1 vue2安装引用

安装

npm i element-ui -S

引用:在main.js中添加如下代码

import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';

Vue.use(ElementUI);

 

2.1.2 vue3的安装引用

安装

npm install element-plus --save

引用:在main.js中添加如下代码

import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'

Vue.use(ElementPlus)

 

2.2 使用

将代码复制到自己组件即可,唯一要注意的就是代码复制全了

 1 <template>
 2   <div id="app">
 3     <i class="el-icon-edit"></i>
 4     <i class="el-icon-share"></i>
 5     <i class="el-icon-delete"></i>
 6     <el-button type="primary" icon="el-icon-search">搜索</el-button>
 7 
 8     <div>
 9       <el-input placeholder="请输入内容" v-model="input1">
10         <template slot="prepend">Http://</template>
11       </el-input>
12     </div>
13     <div style="margin-top: 15px;">
14       <el-input placeholder="请输入内容" v-model="input2">
15         <template slot="append">.com</template>
16       </el-input>
17     </div>
18     <div style="margin-top: 15px;">
19       <el-input placeholder="请输入内容" v-model="input3" class="input-with-select">
20         <el-select v-model="select" slot="prepend" placeholder="请选择">
21           <el-option label="餐厅名" value="1"></el-option>
22           <el-option label="订单号" value="2"></el-option>
23           <el-option label="用户电话" value="3"></el-option>
24         </el-select>
25         <el-button slot="append" icon="el-icon-search"></el-button>
26       </el-input>
27     </div>
28   </div>
29 </template>
30 
31 <style>
32 .el-select .el-input {
33   width: 130px;
34 }
35 .input-with-select .el-input-group__prepend {
36   background-color: #fff;
37 }
38 
39 
40 </style>

效果:

 

 

3.vuex使用

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式 + 库。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。

说白了就是一个全局存储数据的,我们项目的任意组件中都可以使用vuex中定义的数据和方法

 

 

3.1 vuex的安装

npm install vuex@next --save

3.2 vuex的引用

在vue项目的src目录下创建store文件夹并创建index.js文件,文件内容如下


import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
state: {
// 存放变量
},
getters: {
// TBD
},
mutations: {
// 存放方法,对state中的变量进行操作
},
actions: {
// 存放方法,调用mutations中的方法
},
modules: {
// TBD
}
})
 

然后再main.js中加入如下代码

import store from './store'

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

 3.3 vuex的使用

小案例

store/index.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
    state: {
        // 存放变量
        sum: 0
    },
    getters: {
        // TBD
    },
    mutations: {
        // 存放方法,对state中的变量进行操作
        // 方法有两个参数:state就是上面的state和数据
        Add(state, value) {
            state.sum += value
        }
    },
    actions: {
        // 存放方法,调用mutations中的方法
        // 方法有两个参数:上下文和数据
        add(context,value){
            // 通过上下文调用mutations中的方法
            context.commit('Add', value)
        }
    },
    modules: {
        //  TBD
    }
})

main.vue

<template>
  <div id="app">
    <el-button type="success" @click="handle">+2</el-button>
    <!--   在任意组件中获取store中的state的数据 -->
    vuex中的store中的数值:{{ this.$store.state.sum }}
  </div>
</template>

<script>
export default {
  name: 'App',
  data() {
    return {}
  },
  methods: {
    handle() {
      // 调用store actions中定义的方法
      this.$store.dispatch('add', 2)
    }
  }
}
</script>
<style>


</style>

 

效果如下:

我们想要获取state中的变量

this.$store.state.变量

如果想要修改state的变量就比较麻烦

// 1.在mutations定义方法,完成对变量的修改
// 2. 在actions中定义方法,调用mutations中的方法
// 3. 在外部组件,使用this.$store.dispatch('actions中的方法', 数据)

 

4.vue-router的使用

原文地址:http://www.cnblogs.com/victor1234/p/16862994.html

1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长! 2. 分享目的仅供大家学习和交流,请务用于商业用途! 3. 如果你也有好源码或者教程,可以到用户中心发布,分享有积分奖励和额外收入! 4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解! 5. 如有链接无法下载、失效或广告,请联系管理员处理! 6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需! 7. 如遇到加密压缩包,默认解压密码为"gltf",如遇到无法解压的请联系管理员! 8. 因为资源和程序源码均为可复制品,所以不支持任何理由的退款兑现,请斟酌后支付下载 声明:如果标题没有注明"已测试"或者"测试可用"等字样的资源源码均未经过站长测试.特别注意没有标注的源码不保证任何可用性