美文网首页
vuex 快速上手

vuex 快速上手

作者: 晴_eeca | 来源:发表于2018-03-22 15:31 被阅读22次

一. 引用

引入Vuex(前提是已经用Vue脚手架工具构建好项目)

1.安装

npm install vuex --save

要注意的是这里一定要加上 –save,因为你这个包我们在生产环境中是要使用的。

2、新建一个store文件夹(这个不是必须的),并在文件夹下新建store.js文件,文件中引入我们的vue和vuex。

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

export default new vuex.Store({
      。。。
})

3、在main.js 中引入新建的vuex文件

import store from './store'

4、再然后 , 在实例化 Vue对象时加入 store 对象 :

new Vue({
      el: '#app',
      store,//使用store
      template: '<App/>',
      components: { App }
    })

二. Vue 理解

Vuex 使用 单一状态树,通俗理解就是一个应用的数据集合,可以想象为一个“前端数据库”,让其在各个页面上实现数据的共享,并且可操作

Vuex 规定,属于应用层级的状态只能通过 Mutation 中的方法来修改,而派发 Mutation 中的事件只能通过 action。

从左到右,从组件出发,组件中调用 action,在 action 这一层级我们可以和后台数据交互,比如获取初始化的数据源,或者中间数据的过滤等。然后在 action 中去派发 Mutation。Mutation 去触发状态的改变,状态的改变,将触发视图的更新。

注意事项
数据流都是单向的

组件能够调用 action

action 用来派发 Mutation

只有 mutation 可以改变状态

store 是响应式的,无论 state 什么时候更新,组件都将同步更新
image

三. 使用

1. State

在 store 中的 state 对象,可以理解为 Vue 实例中的 data 对象,它用来保存最基本的数据。

import Vue from 'Vue';
import Vuex from 'Vuex';
Vue.use(Vuex);
let store = new Vuex.Store({
    state: {
        stateA: 'a',
        stateB: 'b',
        stateC: 'c'
    }
});
console.log(store.state.stateA); // a

在 Vue 中获取 store 中的状态

let app = new Vue({
   el: '#demo',
    template: `
{{myState}}
`,
    computed: {
         myState() {
            return store.state.stateA;
        }
    }
});

2. Mutations

更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。
mutation中写有修改数据的逻辑。
另外mutation里只能执行同步操作。

mutations:{
        getConfig(state){
            let _this = this;
            let payload = {
                timestamp: 123123412414142,
                principal: 1000
            };
            let cheaders = {
                headers: {
                    appname:'walletandroid',
                    appversion:'3',
                    signature:'eced94b3244b16ed81d2517589baae7e90727382b7c56750cc517415583c8a5b'
                }
            };
            Vue.http.post('http://apitest.wewallet.info/wallet/v1/roulette/123455/fsdfasdfa/config', JSON.stringify(payload), cheaders)
                .then((response) => {
                    state.datalist = response.body.data;
                    console.log(state.datalist)
                });
        },
        getTry(state){
            let _this = this;
            let payload = {
                timestamp: 123123412414142,
                principal: 1000
            };
            let cheaders = {
                headers: {
                    appname:'walletandroid',
                    appversion:'3',
                    signature:'eced94b3244b16ed81d2517589baae7e90727382b7c56750cc517415583c8a5b'
                }
            };
            Vue.http.post('http://apitest.wewallet.info/wallet/v1/roulette/123455/fsdfasdfa/try', JSON.stringify(payload), cheaders)
                .then((response) => {
                    state.coins = response.body.data.coins;
                })
        },
    },

想要改变状态的时候都是用store.commit的方式

带参数提交
created() {
      this.$store.commit('change',item);
}
mutations:{
      changeData(state,item){
          state.data = item
      }
}
在组件中提交 Mutations

你可以在组件中使用 this.$store.commit(‘xxx’) 提交 mutation,或者使用 mapMutations 辅助函数将组件中的 methods 映射为 store.commit 调用(需要在根节点注入 store)。

created() {      //vue created钩子函数,在页面加载时执行
            this.$store.dispatch('addCount')
        },

3. Action

action,动作。
对于store中数据的修改操作动作在action中提交。
其实action和mutation类似,但是action提交是mutation,并不直接修改数据,而是触发mutation修改数据。

actions:{
        config({commit}){
            commit('getConfig')
        },
        try({commit}){
            commit('getTry')
        }
    },

示例

store的index.js文件

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


export default new vuex.Store({
    state:{
        datalist:[],
        coins:''
    },
    mutations:{
        getConfig(state){
            let _this = this;
            let payload = {
                timestamp: 123123412414142,
                principal: 1000
            };
            let cheaders = {
                headers: {
                    appname:'android',
                    appversion:'3',
                    signature:'eced94b3244b16ed81d2517cc517415583c8a5b'
                }
            };
            Vue.http.post('http://apitestv1/roulette/123455/fsdfasdfa/config', JSON.stringify(payload), cheaders)
                .then((response) => {
                    state.datalist = response.body.data;
                    console.log(state.datalist)
                });
        },
        getTry(state){
            let _this = this;
            let payload = {
                timestamp: 123123412414142,
                principal: 1000
            };
            let cheaders = {
                headers: {
                    appname:'walletandroid',
                    appversion:'3',
                    signature:'eced94b3244b16ec517415583c8a5b'
                }
            };
            Vue.http.post('http://apitest/v1/roulette/123455/fsdfasdfa/try', JSON.stringify(payload), cheaders)
                .then((response) => {
                    state.coins = response.body.data.coins;
                })
        },
    },
    actions:{
        config({commit}){
            commit('getConfig')
        },
        try({commit}){
            commit('getTry')
        }
    },
})

组件

<template>
       <div class="box">
              <div>{{getList}}</div>
              <div>{{getCoins}}</div>
       </box>
</template>
computed:{
       getList(){
            return this.datalist = this.$store.state.datalist
       }, 
       getCoins(){
            return this.coins = this.$store.state.coins
       } 
},
created() {
       this.$store.dispatch('config');
       this.$store.dispatch('try');
},

相关文章

  • vuex 快速上手

    一. 引用 引入Vuex(前提是已经用Vue脚手架工具构建好项目) 1.安装 2、新建一个store文件夹(这个不...

  • 快速上手Vuex

    学过Vue的伙伴们都知道在简单的场景下,父子组件的通信可以用Props完成,孩子组件与父组件之间可以emit(触发...

  • 快速上手vuex

    Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应...

  • Vuex快速上手

    Vuex快速上手 通俗的解释:是一种最好的非父子组件传值的一种方案。官方解释:Vuex是一个公共状态管理(公共的内...

  • vuex入门实例2

    vuex入门实例2 这章节我准备以requirejs模块化,讲解下如何快速上手vuex 源码地址 工程代码结构如下...

  • Vuex 快速入门上手教程

    一. 什么是Vuex? Vuex是一个专门为Vue.js应用程序开发的状态管理模式, 它采用集中式存储管理所有组件...

  • vuex 上手使用

    什么是vuex Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。 每一个 Vuex 应用的核心就是...

  • Vuex简单上手

    Vuex Vuex是Vue.js应用的状态管理模式目前开发项目中,主要用于保存组件状态,保证兄弟组件间的通信。 首...

  • Masonry介绍与使用实践:快速上手Autolayout

    Masonry介绍与使用实践:快速上手Autolayout Masonry介绍与使用实践:快速上手Autolayout

  • Vuex入门到上手

    一、前言 当我们的应用遇到多个组件共享状态时,会需要多个组件依赖于同一状态。传参的方法对于多层嵌套的组件将会非常繁...

网友评论

      本文标题:vuex 快速上手

      本文链接:https://www.haomeiwen.com/subject/xxuaqftx.html