vuex基础知识

  • 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
  }
})


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

正函数 

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值