Vue模块化+异步执行+状态管理工具(使用流程)
这个文章主要讲解的是vue中使用vuex的模块化,和异步执行方法,以及安装卸载步骤,详细全面+保姆!
首先配置好vue项目使用yarn下载vuex 首先下载yarn
下载yarn ↓ 两种方式任意一个就可以
npm i yarn
npm install -g yarn
然后下载vuex
yarn add vuex@3.6.2 //这个版本比较合适,如果不指定版本就不用@
卸载: yarn remove vuex@next
运行 yarn serve
项目中 main.js中
import store from '@/store/index'
//导入store 文件并挂载
new Vue({
store,
}).$mount('#app')
在组件中
<template>
<div class="home">
<button @click="add">登录</button>
</div>
</template>
<script>
export default {
name: 'HomeView',
methods:{
add(){
// 调用my_goods模块的AcSync异步方法 并传递数据666
this.$store.dispatch('my_goods/AcSync',666)
}
}
}
</script>
在index.js中
import Vue from 'vue'
import Vuex from 'vuex'
import Goods from '@/store/modules/goods'
Vue.use(Vuex)
const store = new Vuex.Store({
actions:{
},
modules:{
// 模块中定义组件名和导入的路径名
// 组件名是使用的:真实的导入路径
'my_goods':Goods
}
})
export default store
模块中
export default {
// 这一步不要忘记 很容易遗漏
// 开启命名空间 防止命名冲突
namespaced:true,
// 定义的数据
state:{
token:null
},
// 方法
mutations:{
addToken(state,v){
// 接受到数据后修改数据 完成异步方法
state.token=v
console.log(state.token);
}
},
// 异步方法
actions:{
AcSync(context,v){
// 所有的方法
console.log(context);
// 传递的数据
console.log(v);
// 在异步中获取方法 传递数据
context.commit('addToken',v)
}
}
}