- state: 用来存储数据的 相当于data,// 组件间公共数据部分
- mutations: 需要改变state中的数据时,要在mutation里定义改变的⽅法
- actions: 当state里面的数据需要异步操作是时要在 actions里面定义方法
- 在actions中请求数据 需要赋值给state时 要调用mutions方法(
在actions 中定义commit(‘mutions中的方法名’,传递的参数)
然后再mutions中进行赋值
)
//获取数据
const actions = {
async geTodos({ commit }) {
//获取数据
const respoense = await axios.get('http://jsonplaceholder.typicode.com/todos');
console.log(respoense.data);
commit('initList',respoense.data)
},
}
const mutations = {
// initList(state,todos){
// state.todos=todos
// },
initList:(state,todos)=>(state.todos = todos)
};
2.基本使用
state: {
count:0
},
count 是我vuex state 里面存储的数据
在其他页面获取方法如下:
//方法一在计算属性里面获取
computed:{
count(){
return this.$store.state.count
}
//方法二.使用辅助函数
impor {mapState} from "vuex"; //引入
computed:{
...mapState({
count :'count'
})
}
调用vuex 里面的方法
methods:{
add(){
this.$store.commit(‘add’)
//或者使用辅助函数
…mapMutations([‘add’])
}
}
actions异步操作
delay(context){
setTimeout((=>{
context.commit(‘add’)
}))
调用 this.$store.dispatch(‘delay’)
}
getters计算属性
getters:{
debluecount(state){
return state.count*2
}
},
调用使用辅助函数
才computed里面
...mapGetters([
'debluecount'
])
``
+ 模块化的使用
export default{
state:{
},
getters:{},
mutations:{},
actions:{}
}
//在index,js 文件下引入
import Vue from 'vue'
import Vuex from 'vuex'
import text from './model/text.js'
Vue.use(Vuex)
export default new Vuex.Store({
modules: {
text
}
})