[三分钟笔记]vuex使用简洁笔记

0、vuex是什么:全局的状态存储仓库

1、为何要用:主要可以解决兄弟、或无关联组件之间、全局的数据存储传递的问题

2、使用方法:

state属性 可以看做全局的data

getters属性 可以看做全局的computed属性

mutations 可以看做全局的methods方法

actions 可以看做全局的异步调用methods方法

       modules  一整个模块 略

3、代码引入:main.js

    import Vuex from 'vuex'
    Vue.use(Vuex)
    const store = new Vuex.Store({
        state: { // 把state看出全局的data
            name: 'xl'
        },
        getters: { // 全局的computed属性
             fullName: state =>{
                 return '我的名字叫'+state.name
             }
        },
        mutations: { //全局的methods方法    回调函数使用必须用this.$store.commit()
            changeNameFun(state, payload) {
                state.name = payload
            }
        },
        actions: {  //提交mutations  允许异步操作 
            changeNameFunAsync(context, payload) {
                setTimeout( ()=>{
                    context.commit('changeNameFun', payload)
                }, 2000);
            }
        }
    })
    new Vue({
        el: '#app',
        store,  // 将store挂载到vue实例当中
        render: h=> h(App)
    })
    

 

3.1、代码引入 另一种写法 将store分离出来新建一个store.js页  然后向外导出整个vuex对象

main.js文件引入
import store from './store'; //在同级新建store.js文件  引入store对象
new Vue({
  router,
  store,  // 将store挂载到vue实例当中
  render: h => h(App)
}).$mount('#app')
新建的文件store.js

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)


export default new Vuex.Store({
    state: { // 把state看出全局的data
            name: 'xl'
    },
    getters: { // 全局的computed属性
         fullName: state =>{
             return '我的名字叫'+state.name
         }
    },
    mutations: { //全局的methods方法    回调函数使用必须用this.$store.commit()
            changeNameFun(state, payload) {
                state.name = payload
            }
    },
    actions: {  //提交mutations  允许异步操作 
        changeNameFunAsync(context, payload) {
            setTimeout( ()=>{
                 context.commit('changeNameFun', payload); //在actions里调mutations属性的函数,第一个参数是方法名,第二个是数据
            }, 2000);
        }
    }
})

4、在page.vue中的使用

               this.$store.state.name     //定义的变量name
               this.$store.getters.fullName   //定义的getters fullName
               changeNameFun() { this.$store.commit('changeNameFun', 'xl小姐姐') } // 通过commit方法,传进去第一个参是方法名,第二个参是数据
               changeNameFunAsync() { this.$store.dispatch('changeNameFunAsync', 'xl小姐姐爱coding')}  //通过dispatch方法,传进去第一个参是方法名,第二个参是数据

 5、modules  略

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值