<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Vue &#8211; chang的个人博客</title>
	<atom:link href="https://www.qiqin-chang.cn/category/front/vue/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.qiqin-chang.cn</link>
	<description></description>
	<lastBuildDate>Sat, 03 Jan 2026 05:08:02 +0000</lastBuildDate>
	<language>zh-Hans</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>https://www.qiqin-chang.cn/wp-content/uploads/2025/04/cropped-无背景-圆形-32x32.png</url>
	<title>Vue &#8211; chang的个人博客</title>
	<link>https://www.qiqin-chang.cn</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Pinia-状态管理库</title>
		<link>https://www.qiqin-chang.cn/pinia/</link>
					<comments>https://www.qiqin-chang.cn/pinia/#respond</comments>
		
		<dc:creator><![CDATA[乐章]]></dc:creator>
		<pubDate>Sun, 28 Dec 2025 19:41:36 +0000</pubDate>
				<category><![CDATA[Vue]]></category>
		<guid isPermaLink="false">http://www.qiqin-chang.cn/?p=581</guid>

					<description><![CDATA[介绍：Pinia是Vue的专属状态管理库，它允许你跨组件或页面共享状态 安装： 配置： 配置Piain: ma [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>介绍：Pinia是Vue的专属状态管理库，它允许你跨组件或页面共享状态</p>



<h2 class="wp-block-heading">安装：</h2>



<pre class="wp-block-code"><code>npm install pinia   </code></pre>



<h2 class="wp-block-heading">配置：</h2>



<h3 class="wp-block-heading">配置Piain:</h3>



<p>main.js：</p>



<pre class="wp-block-code"><code>//Pinia-状态管理库
import {createPinia} from 'pinia'
​
const pinia = createPinia()
​
app.use(pinia)</code></pre>



<h3 class="wp-block-heading">定义仓库：</h3>



<p>src/store/token.js</p>



<pre class="wp-block-code"><code>import { defineStore } from 'pinia'
​
export const useTokenStore = defineStore('token', {
 &nbsp; &nbsp;state: () =&gt; ({
 &nbsp; &nbsp; &nbsp; &nbsp;token: localStorage.getItem('chang-token') || ''
 &nbsp;  }),
 &nbsp; &nbsp;getters: {
 &nbsp; &nbsp; &nbsp; &nbsp;getToken: (state) =&gt; state.token,
 &nbsp; &nbsp; &nbsp; &nbsp;isLogin: (state) =&gt; !!state.token
 &nbsp;  },
 &nbsp; &nbsp;actions: {
 &nbsp; &nbsp; &nbsp; &nbsp;setToken(token) {
 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;this.token = token
 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;localStorage.setItem('chang-token', token) // ✅ 同步到本地存储
 &nbsp; &nbsp; &nbsp;  },
 &nbsp; &nbsp; &nbsp; &nbsp;removeToken() {
 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;this.token = ''
 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;localStorage.removeItem('chang-token') // ✅ 清除本地存储
 &nbsp; &nbsp; &nbsp;  }
 &nbsp;  }
})</code></pre>



<h2 class="wp-block-heading">使用：</h2>



<pre class="wp-block-code"><code>import {useTokenStore} from "@/stores/token.js";
​
const tokenStore = useTokenStore();
​
eg:
tokenStore.setToken(res.data.token);
config.headers&#91;'token'] = tokenStore.token;</code></pre>



<h1 class="wp-block-heading">Persist-Pinia持久化插件:</h1>



<p>介绍：Pinia默认存储在内存，当浏览器刷新时会丢失数据，Persist插件可以将pinia中的数据持久化储存</p>



<h2 class="wp-block-heading">安装：</h2>



<pre class="wp-block-code"><code>npm install pinia-persistedstate-plugin</code></pre>



<h2 class="wp-block-heading">配置：</h2>



<h3 class="wp-block-heading">配置Persist:</h3>



<p>main.js：</p>



<pre class="wp-block-code"><code>//Persist-Pinia持久化插件
import {createPersistedState} from "pinia-persistedstate-plugin";
​
const persist = createPersistedState();
​
pinia.use(persist)</code></pre>



<h3 class="wp-block-heading">定义仓库：</h3>



<p>src/store/token.js：</p>



<pre class="wp-block-code"><code>import { defineStore } from 'pinia'
import { ref } from "vue";
​
export const useTokenStore = defineStore('token', ()=&gt;{
 &nbsp; &nbsp;//定义状态内容
​
 &nbsp; &nbsp;//1.响应式变量
 &nbsp; &nbsp;const token = ref('')
​
 &nbsp; &nbsp;//2.定义一个函数，修改token的值
 &nbsp; &nbsp;const setToken = (newToken) =&gt; {
 &nbsp; &nbsp; &nbsp; &nbsp;token.value = newToken
 &nbsp;  }
​
 &nbsp; &nbsp;//3.函数，移除token的值
 &nbsp; &nbsp;const removeToken = () =&gt; {
 &nbsp; &nbsp; &nbsp; &nbsp;token.value = ''
 &nbsp;  }
​
 &nbsp; &nbsp;return {
 &nbsp; &nbsp; &nbsp; &nbsp;token,setToken,removeToken,
 &nbsp;  }
},{
 &nbsp; &nbsp;persist:true //持久化存储
})</code></pre>



<h2 class="wp-block-heading"><strong>使用：</strong></h2>



<pre class="wp-block-code"><code>import {useTokenStore} from "@/stores/token.js";
​
const tokenStore = useTokenStore();
​
eg:
tokenStore.setToken(res.data.token);
config.headers&#91;'token'] = tokenStore.token;</code></pre>
]]></content:encoded>
					
					<wfw:commentRss>https://www.qiqin-chang.cn/pinia/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>VueRouter-路由管理</title>
		<link>https://www.qiqin-chang.cn/vuerouter/</link>
					<comments>https://www.qiqin-chang.cn/vuerouter/#respond</comments>
		
		<dc:creator><![CDATA[乐章]]></dc:creator>
		<pubDate>Sun, 28 Dec 2025 19:23:37 +0000</pubDate>
				<category><![CDATA[Vue]]></category>
		<category><![CDATA[前端]]></category>
		<guid isPermaLink="false">http://www.qiqin-chang.cn/?p=575</guid>

					<description><![CDATA[官网：https://router.vuejs.org/zh/guide/ 路由配置： router/inde [&#8230;]]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading">官网：<a href="https://router.vuejs.org/zh/guide/">https://router.vuejs.org/zh/guide/</a></h2>



<h2 class="wp-block-heading">路由配置：</h2>



<p>router/index.js：</p>



<pre class="wp-block-code"><code>import { createRouter, createWebHistory } from 'vue-router'
​
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: &#91;
    {path: '/', redirect: '/manager/home'},
    {path: '/manager', component: ()=>import('../views/Manager.vue'),children:&#91;
        {path: 'home', name: 'home',meta:{title:'主页'}, component: () => import('../views/Home.vue'),},
        {path: 'test', name: 'test',meta:{title:'测试页'}, component: () => import('../views/Test.vue'),},
      ]
    },
    {path: '/404', name: 'NotFound',meta:{title:'404找不到页面'}, component: () => import('../views/404.vue'),},
    {path:'/:pathMatch(.*)',redirect:'/404'},
  ],
})
​
//beforeEach表示跳转之前的操作
router.beforeEach((to, from, next) => {
  document.title = to.meta.title;
  next();
})
​
export default router</code></pre>



<h2 class="wp-block-heading">路由跳转：</h2>



<h3 class="wp-block-heading">标签式跳转：</h3>



<pre class="wp-block-code"><code>&lt;RouterLink to="/test">通过router跳转到Test.vue&lt;/RouterLink></code></pre>



<h3 class="wp-block-heading">编程式跳转：</h3>



<p>导入router：</p>



<pre class="wp-block-code"><code>import router from "@/router/index.js"</code></pre>



<p>跳转：</p>



<pre class="wp-block-code"><code>&lt;el-button type="primary" @click="router.push('/test')">使用push跳转到test页面&lt;/el-button>
&lt;el-button type="primary" @click="router.replace('/test')">使用replace跳转到test页面&lt;/el-button></code></pre>



<ul class="wp-block-list">
<li>push：跳转方式-添加路由，跳转后可以返回</li>



<li>replace：跳转方式-替换路由，跳转后无法返回</li>
</ul>



<p>返回：</p>



<pre class="wp-block-code"><code>&lt;el-button type="primary" @click="router.back()">返回主页&lt;/el-button></code></pre>



<h2 class="wp-block-heading">路由传参：</h2>



<p>发送：</p>



<pre class="wp-block-code"><code>&lt;!--方式一-->
&lt;el-button type="primary" @click="router.push('/test?id=1&amp;name=chang')">路由传参方式1&lt;/el-button>
&lt;!--方式二-->
&lt;el-button type="primary" @click="router.push({path:'/test',query:{id:1,name:'chang'}})">路由传参方式2&lt;/el-button></code></pre>



<p>接收：</p>



<pre class="wp-block-code"><code>import {reactive} from "vue";
import router from "@/router/index.js";
​
  const data = reactive({
    id:router.currentRoute.value.query.id,
    name:router.currentRoute.value.query.name,
  })
​
  console.log('获取到传递过来的id='+data.id);
  console.log('获取到传递过来的name='+data.name);</code></pre>



<h2 class="wp-block-heading">嵌套路由：</h2>



<pre class="wp-block-code"><code>{path: '/manager', component: ()=>import('../views/Manager.vue'),children:&#91;
    {path: 'home', name: 'home',meta:{title:'主页'}, component: () => import('../views/Home.vue'),},
    {path: 'test', name: 'test',meta:{title:'测试页'}, component: () => import('../views/Test.vue'),},
]},</code></pre>



<ul class="wp-block-list">
<li>父级页面可以通过&lt;RouterView/>展现子级页面内容</li>



<li>在嵌套路由中子级路由不需要写前面的 / 会自动添加</li>
</ul>



<h2 class="wp-block-heading">路由守卫：</h2>



<p>修改网页标题：</p>



<pre class="wp-block-code"><code>//to：用于对跳转之后的对象进行操作
//from：用于对跳转前的对象进行操作
//next()：调用该方法后，才能进入下一个钩子
//beforeEach表示跳转之前的操作
router.beforeEach((to, from, next) => {
  document.title = to.meta.title;
  next();
})</code></pre>



<p>meta：补充路由参数的对象</p>



<h2 class="wp-block-heading">404页面：</h2>



<p>定义404路由：</p>



<pre class="wp-block-code"><code>{path: '/404', name: 'NotFound',meta:{title:'404找不到页面'}, component: () => import('../views/404.vue'),},
{path:'/:pathMatch(.*)',redirect:'/404'}, &lt;!--输入错误时统一到达404页面--></code></pre>



<p>定义404页面：</p>



<pre class="wp-block-code"><code>&lt;template>
  &lt;div style="text-align: center">
    &lt;img src="../assets/404.png" alt="">
    &lt;div>
      &lt;el-button type="primary" style="width: 150px;height: 50px;font-size: 20px" @click="gohome">返回主页&lt;/el-button>
    &lt;/div>
  &lt;/div>
&lt;/template>
&lt;script setup>
import router from "@/router/index.js";
const gohome = () => {
  location.href = "/manager/home";
}
&lt;/script>
&lt;style scoped>
&lt;/style></code></pre>
]]></content:encoded>
					
					<wfw:commentRss>https://www.qiqin-chang.cn/vuerouter/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>密码保护：Vue</title>
		<link>https://www.qiqin-chang.cn/vue/</link>
					<comments>https://www.qiqin-chang.cn/vue/#respond</comments>
		
		<dc:creator><![CDATA[乐章]]></dc:creator>
		<pubDate>Mon, 11 Aug 2025 05:30:04 +0000</pubDate>
				<category><![CDATA[Vue]]></category>
		<category><![CDATA[前端]]></category>
		<guid isPermaLink="false">http://www.qiqin-chang.cn/?p=551</guid>

					<description><![CDATA[无法提供摘要。这是一篇受保护的文章。]]></description>
										<content:encoded><![CDATA[<form action="https://www.qiqin-chang.cn/znyz" class="post-password-form" method="post"><input type="hidden" name="redirect_to" value="https://www.qiqin-chang.cn/vue/" /></p>
<p>此内容受密码保护。如需查阅，请在下方输入密码。</p>
<p><label for="pwbox-551">密码： <input name="post_password" id="pwbox-551" type="password" spellcheck="false" required size="20" /></label> <input type="submit" name="Submit" value="提交" /></p>
</form>
]]></content:encoded>
					
					<wfw:commentRss>https://www.qiqin-chang.cn/vue/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>ElementUI-组件库</title>
		<link>https://www.qiqin-chang.cn/elementui-%e7%bb%84%e4%bb%b6%e5%ba%93/</link>
					<comments>https://www.qiqin-chang.cn/elementui-%e7%bb%84%e4%bb%b6%e5%ba%93/#respond</comments>
		
		<dc:creator><![CDATA[乐章]]></dc:creator>
		<pubDate>Mon, 11 Aug 2025 05:26:38 +0000</pubDate>
				<category><![CDATA[Vue]]></category>
		<category><![CDATA[前端]]></category>
		<guid isPermaLink="false">http://www.qiqin-chang.cn/?p=546</guid>

					<description><![CDATA[Vue2官方网站：https://element.eleme.cn/#/zh-CN Vue3官方网站：http [&#8230;]]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading">Vue2官方网站：<a href="https://element.eleme.cn/#/zh-CN">https://element.eleme.cn/#/zh-CN</a></h2>



<h2 class="wp-block-heading">Vue3官方网站：<a href="https://element-plus.org/zh-CN/#/zh-CN">https://element-plus.org/zh-CN/#/zh-CN</a></h2>



<h2 class="wp-block-heading">安装：</h2>



<pre class="wp-block-code"><code>npm install element-ui -S</code></pre>



<h2 class="wp-block-heading">引入:</h2>



<p>在 main.js 中写入以下内容：</p>



<pre class="wp-block-code"><code>//ElementUI-组件库
import Element from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
​
Vue.use(Element)</code></pre>



<h2 class="wp-block-heading">测试引入：</h2>



<pre class="wp-block-code"><code>&lt;el-button&gt;按钮&lt;/el-button&gt;</code></pre>
]]></content:encoded>
					
					<wfw:commentRss>https://www.qiqin-chang.cn/elementui-%e7%bb%84%e4%bb%b6%e5%ba%93/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Axios-http请求</title>
		<link>https://www.qiqin-chang.cn/axios/</link>
					<comments>https://www.qiqin-chang.cn/axios/#respond</comments>
		
		<dc:creator><![CDATA[乐章]]></dc:creator>
		<pubDate>Mon, 11 Aug 2025 05:24:38 +0000</pubDate>
				<category><![CDATA[Vue]]></category>
		<category><![CDATA[前端]]></category>
		<guid isPermaLink="false">http://www.qiqin-chang.cn/?p=542</guid>

					<description><![CDATA[基本安装： npm install axios -S​npm install vue-axios -S 引入： [&#8230;]]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading">基本安装：</h2>



<pre class="wp-block-preformatted">npm install axios -S<br>​<br>npm install vue-axios -S</pre>



<h2 class="wp-block-heading">引入：</h2>



<p>在 main.js 中写入以下内容：</p>



<pre class="wp-block-preformatted">//Axios-http请求<br>import axios from 'axios'<br>import VueAxios from 'vue-axios'<br>​<br>Vue.use(axios,VueAxios)</pre>



<h2 class="wp-block-heading">使用方法：</h2>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>请求</th></tr></thead><tbody><tr><td>axios.get(url[, config])</td></tr><tr><td>axios.post(url[, data[, config]])</td></tr><tr><td>axios.delete(url[, config])</td></tr><tr><td>axios.head(url[, config])</td></tr><tr><td>axios.options(url[, config])</td></tr><tr><td>axios.put(url[, data[, config]])</td></tr><tr><td>axios.patch(url[, data[, config]])</td></tr></tbody></table></figure>



<ul class="wp-block-list">
<li>config &#8211; 选项对象、例如查询参数、请求头&#8230;</li>



<li>data &#8211; 请求体数据、最常见的是 json 格式数据</li>



<li>get、head 请求无法携带请求体，这应当是浏览器的限制所致（xhr、fetch api 均有限制）</li>



<li>options、delete 请求可以通过 config 中的 data 携带请求体</li>
</ul>



<p>使用：</p>



<pre class="wp-block-preformatted">&lt;template&gt;<br> &nbsp; &nbsp;&lt;div&gt;<br> &nbsp; &nbsp; &nbsp; &nbsp;&lt;input type="button" value="获取远程数据" @click="sendReq()"&gt;<br> &nbsp; &nbsp;&lt;/div&gt;<br>&lt;/template&gt;<br>&lt;script&gt;<br>import axios from 'axios'<br>const options = {<br> &nbsp; &nbsp;methods: {<br> &nbsp; &nbsp; &nbsp; &nbsp;async sendReq() {<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// 1. 基础请求 get, post<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;const resp = await axios.post('/api/a2');<br>​<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// 2. 携带请求头<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;const resp = await axios.post('/api/a3',{},{<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;headers:{<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Authorization:'abc'<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;  }<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;  });<br>​<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// 3.携带请求参数<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// 3.1 不想自己拼串、处理特殊字符、就用下面的办法<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;const resp = await axios.post('/api/a4', {}, {<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;params: {<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;name:'&amp;&amp;&amp;&amp;',<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;age: 20<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;  }<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;  });<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// 3.2 发送请求时携带查询参数 ?name=xxx&amp;age=xxx<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;const name = encodeURIComponent('&amp;&amp;&amp;');<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;const age = 18;<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;const resp = await axios.post('/api/a4?name=${name}&amp;age=${age}');//``<br>​<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// 4.携带请求体<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// 4.1 用请求体发数据，格式为 json (推荐)<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;const resp = await axios.post('/api/a5json', {<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;name: '王五',<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;age: 50<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;  });<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// 4.2 用请求体发数据，格式为 urlencoded<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;const params = new URLSearchParams();<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;params.append("name", "张三");<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;params.append("age", 24)<br>​<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;const resp = await axios.post('/api/a4', params);<br>​<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// 4.3 用请求体发数据，格式为 multipart<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;const params = new FormData();<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;params.append("name", "李四");<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;params.append("age", 30);<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;const resp = await axios.post('/api/a5', params);<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;console.log(resp);<br> &nbsp; &nbsp; &nbsp;  }<br> &nbsp;  }<br>};<br>export default options;<br>&lt;/script&gt;</pre>



<h2 class="wp-block-heading">使用实例：</h2>



<p>说明：为请求提供默认配置</p>



<pre class="wp-block-preformatted">const _axios = axios.create(config);</pre>



<ul class="wp-block-list">
<li>axios 对象可以直接使用，但使用的是默认的设置</li>



<li>用 axios.create 创建的对象，可以覆盖默认设置，config 见下面说明</li>
</ul>



<p>常见的 config 项有</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>名称</th><th>含义</th></tr></thead><tbody><tr><td>baseURL</td><td>将自动加在 url 前面</td></tr><tr><td>headers</td><td>请求头，类型为简单对象</td></tr><tr><td>params</td><td>跟在 URL 后的请求参数，类型为简单对象或 URLSearchParams</td></tr><tr><td>data</td><td>请求体，类型有简单对象、FormData、URLSearchParams、File 等</td></tr><tr><td>withCredentials</td><td>跨域时是否携带 Cookie 等凭证，默认为 false</td></tr><tr><td>responseType</td><td>响应类型，默认为 json</td></tr></tbody></table></figure>



<p>例：</p>



<pre class="wp-block-preformatted">const _axios = axios.create({<br> &nbsp; &nbsp;baseURL: 'http://localhost:8080',<br> &nbsp; &nbsp;withCredentials: true<br>});<br>await _axios.post('/api/a6set')<br>await _axios.post('/api/a6get')</pre>



<ul class="wp-block-list">
<li>生产环境希望 xhr 请求不走代理，可以用 baseURL 统一修改</li>



<li>希望跨域请求携带 cookie，需要配置 withCredentials: true，服务器也要配置 allowCredentials = true，否则浏览器获取跨域返回的 cookie 时会报错</li>
</ul>



<h2 class="wp-block-heading">响应格式：</h2>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>名称</th><th>含义</th></tr></thead><tbody><tr><td>data</td><td>响应体数据 ⭐️</td></tr><tr><td>status</td><td>状态码 ⭐️</td></tr><tr><td>headers</td><td>响应头</td></tr></tbody></table></figure>



<ul class="wp-block-list">
<li>200 表示响应成功</li>



<li>400 请求数据不正确 age=abc</li>



<li>401 身份验证没通过</li>



<li>403 没有权限</li>



<li>404 资源不存在</li>



<li>405 不支持请求方式 post</li>



<li>500 服务器内部错误</li>
</ul>



<h2 class="wp-block-heading">拦截器：</h2>



<p>请求拦截器：</p>



<pre class="wp-block-preformatted">_axios.interceptors.request.use(<br> &nbsp;function(config) {<br> &nbsp; &nbsp;// 比如在这里添加统一的 headers<br> &nbsp; &nbsp;return config;<br>  },<br> &nbsp;function(error) {<br> &nbsp; &nbsp;return Promise.reject(error);<br>  }<br>);</pre>



<p>响应拦截器：</p>



<pre class="wp-block-preformatted">_axios.interceptors.response.use(<br> &nbsp;function(response) {<br> &nbsp; &nbsp;// 2xx 范围内走这里<br> &nbsp; &nbsp;return response;<br>  },<br> &nbsp;function(error) {<br> &nbsp; &nbsp;// 超出 2xx, 比如 4xx, 5xx 走这里<br> &nbsp; &nbsp;return Promise.reject(error);<br>  }<br>);</pre>
]]></content:encoded>
					
					<wfw:commentRss>https://www.qiqin-chang.cn/axios/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
