• Vue Vuex state mutations


    Vuex
    解决不同组件的数据共享,与数据持久化

    1.npm install vuex --save
    2.新建store.js 并引入vue vuex ,Vue.use(Vuex)
    3.state在vuex中用于存储数据
    var state = {
      count:1
    }
    4.mutations里放的是方法,主要用于改变state中的数据
    var mutations = {
      incCount(){
        ++state.count;
      }
    }
    5.实例化vuex.Store
      consta store = new Vuex.Store({
        state,
        mutations
      })
    6.export default store;
    7.组件A中引入store
    import store from '../store.js'
    8.注册
    mounted(){},
    store
    9.
    通过this.$store.state.count引用属性
    通过this.$store.commit.('incCount'))引用方法

    10.getters类似于计算属性,改变state里面的count数据的时候,触发getters里的方法,获取新的值
    var getters = {
      computedCount : (state)=>{
        return state.count*2
      }
    }

    通过 this.$store.getters.computedCount调用

    11.Action类似于mutation,不同在于Action提交的是mutation,而不是直接改变状态。Action可包含任意异步操作
    var actions = {
      incMutationsCount(context){
        context.commit('incCount') /*执行mutations里的incCount方法*/
      }
    }
    通过this.$store.dispatch('incMutationsCount')调用

    import Vue from 'vue';
    import Vuex from 'vuex';
    Vue.use(Vuex);
    
    var state = {
        count:1
    }
    
    const mutations = {
        run(){
            ++state.count;
        }
    }
    
    const store = new Vuex.Store({
        state,
        mutations
    });
    
    
    
    
    export default store;
    <template>
      <div id="app">
        <router-link to="/home">Home组件</router-link>
        <router-link to="/news">News组件</router-link>
        <hr>
        <router-view></router-view>
      </div>
    </template>
    
    <script>
    export default {
      name: 'app',
      data () {
        return {
          msg: 'Welcome to Your Vue.js App'
        }
      }
    }
    </script>
    
    <style lang="scss">
    
    </style>
    <template>
        <div id="news">
            News组件
            {{this.$store.state.count}}
        </div>
    </template>
    
    
    <script>
    import store from '../utils/store.js'
    export default {
      data() {
              return{}
      },
      store
    };
    </script>
    <template>
       <div id="home">
            Home组件
            {{this.$store.state.count}}
            <br>
            <button @click="addstate()">添加state</button>
        </div>
    </template>
    
    <script>
    import store from '../utils/store.js'
    export default {
      data() {
        return{}
      },
      store,
      methods:{
        addstate(){
          this.$store.commit('run')
        }
      }
    };
    </script>
  • 相关阅读:
    递归的狂想(菜鸟的胡思乱想)
    关于fiddler的使用总结
    关于mac下 sublime 安装配置java及运行java个人建议
    关于VMwareFusion占用内存过多的问题提几点自己的解决方案
    (ubuntu)ubuntu的root密码设置
    Refactoring to Patterns 学习笔记2 为什么要重构?
    Refactoring to Patterns 学习笔记1 什么是重构?
    [转载]数据结构树之红黑树
    【转载】数据结构之图(存储结构、遍历)
    STL库之单链表:forward_list
  • 原文地址:https://www.cnblogs.com/chenyishi/p/9190609.html
Copyright © 2020-2023  润新知