vuex使用规则

vuex是数据统一集中管理的解决档案,避免了vue组件之间传递数据的麻烦,且其state值同样使用双向数据绑定。

下面利用webpack搭建平台。

1. 在根组件中声明


import Vue from 'vue'
import VueX from 'vuex'
import index from './index.vue'
Vue.use(VueX);

const store = new VueX.Store({
    state: {
        count: 1,
        todos: [
            {id: 1, text: '...', done: true},
            {id: 2, text: '...', done: false}
        ]
    }
});
var root = document.createElement('div');
new Vue({
    store,
    render: (h) => h(index)
}).$mount(root);

2. 子组件中使用state

this.$store.state.count;

在子组件中对store.state值的改变会同步体现在其他组件中。

3. 数据统一同步管理mutations

const store = new VueX.Store({
    state: {
        count: 1,
        todos: [
            {id: 1, text: '...', done: true},
            {id: 2, text: '...', done: false}
        ]
    },
    mutations: {
        increment(state,n) {//这里的state参数不管什么形式都是上面的state。
            state.count+=n;
        },
        decrease(state) {
            state.count--;
        }
    }
});

mutations中是对state数据进行统一操作,方便记录数据变化,不允许在子组件中直接操作state,虽然这样操作可以改变state值,但不推荐。
同时mutations中的操作都是同步的。

4. 子组件中使用mutations方法commit

this.$store.commit('increment',5);
this.$store.commit('decrease');

5. 数据统一管理之异步actions

const store = new VueX.Store({
    state: {
        count: 1,
        todos: [
            {id: 1, text: '...', done: true},
            {id: 2, text: '...', done: false}
        ]
    },
     actions:{
         incrementAsync({commit},obj){//这里的commit必须用花括号
            return new Promise(function (resolve,reject) {
                setTimeout(function () {
                    commit('increment',obj.amount);
                    resolve(123);
                },1000)
            })
        }
    }
});

6. 子组件中使用actions方法dispatch

 countAdd() {

        this.$store.dispatch('incrementAsync',{
            amount:10
        }).then(function (data) {
            alert(data);
            console.log(data);
        })
}

7. getter优先处理

const store = new VueX.Store({
    state: {
        count: 1,
        todos: [
            {id: 1, text: '...', done: true},
            {id: 2, text: '...', done: false}
        ]
    },
     getters:{
        doneTodos: state => {//这里的形参不管是什么都代表store.state.
            return state.todos.filter(todo => {return todo.done});
        }
    }
});

8. 子组件中使用getters

this.$store.getters.doneTodos;

9. 子组件中使用map简化store中状态的引用。

 import { mapState } from 'vuex'
 import { mapGetters } from 'vuex'
 import { mapActions } from 'vuex'
  export default {
    computed: {
        ...mapState({
              count:'count'
          }),
          ...mapGetters({
              doneTodos:'doneTodos'
          })
            },
    methods: {
        ...mapActions({
            incrementAsync:'incrementAsync'
        })
    } 
}

这里需用配置babel以解析扩展运算符。
webpack.config.js中添加js解析loader

 {
      test: /\.js/,
      loader: 'babel-loader',
      exclude:/node_modules/
 },

配置.babelrc文件

{
  "presets": [
    ["env", {
      "es2015": { "modules": false }
    }],
    "stage-3"   // 一定不要忘记
  ],
  "plugins": ["transform-runtime"]
}

安装以下依赖

 "babel": "^6.23.0",
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.4",
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-preset-env": "^1.6.1",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-stage-3": "^6.24.1",

此时可在子组件中直接引用。

<p>show count mapState countAlias:{{count}}</p>
<p>show count done todos:{{doneTodos}}</p>
<input type="button" @click="incrementAsync({amount:20})" value="increase aysnc">
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值