zoukankan      html  css  js  c++  java
  • vuex的使用

    vuex的作用:存储公共变量。

    1.首先安装:npm install vuex --save

    2.挂在在vue对象上

    在main文件中引入使用
    
    import store from './store/index.js'
    
    import Vuex from 'vuex'
    
    Vue.use(Vuex)

    3.在src下面新建文件 index.js入口

     index.js内容:

    import Vue from 'vue'
    import Vuex from 'vuex'
    
    Vue.use(Vuex)
    
    export default new Vuex.Store({
      state: {
         msg:'测试'
      },
      mutations: {
         SET_MSG: (state, msg) => {
          state.msg = msg
        },
      },
      actions: {
    
      },
      getters
    })

    访问说明:

    state相当于 组件中的data 里面存储变量

    mutations:相当于methods 是一些数据的处理方法

    getters:相当于过滤器

    在组件中使用state的方法同router相似

    使用:this.$store.state.变量名  就可以获取 与赋值

    在插值表达式中{{ $store.state.变量名 }}

    三个常用辅助函数 mapstate  mapActions  mapMutations

     如果想获取上面state里面的msg值,一般做法是 this.$store.state.msg 这样写起来比较麻烦,用辅助函数的话就变成:

    <template>
      <div>
        
      </div>
    </template>
    <script type="text/javascript">
      import { mapState } from 'vuex';
      export default {
        data() {
          return {
            
          }
        },
        methods: {
          
        },
        computed: {
            ...mapState({
              msg: msg => state.msg
            })
        },
        mounted() {
          console.log(this.msg); 
        }
      }
    </script>

    同样 如果不使用 mapMutations的话,调用mutations里面的方法时这样:this.$store.commit('SET_MSG', '哈哈')。使用了mapMutation后变成:

    <template>
      <div>
      </div>
    </template>
    <script type="text/javascript">
      import { mapMutations } from 'vuex';
      export default {
        data() {
          return {
            
          }
        },
        created() {
          this.SET_MSG('123');
        },
        methods: {
          ...mapMutations({
            'SET_MSG': 'SET_MSG'
          }),
      }
    </script>
  • 相关阅读:
    HDU 1560 DNA sequence (迭代加深搜索)
    POJ-1077 HDU 1043 HDU 3567 Eight (BFS预处理+康拓展开)
    CSUST 1011 神秘群岛 (Dijkstra+LCA)
    LCA 倍增
    HDU 1003 Max Sum 求区间最大值 (尺取法)
    Codeforce 867 C. Ordering Pizza (思维题)
    POJ 3349 Snowflake Snow Snowflakes (Hash)
    POJ 2774 Long Long Message (Hash + 二分)
    POJ 1200 Crazy Search (Hash)
    前端面试总结(转)
  • 原文地址:https://www.cnblogs.com/bin521/p/13509133.html
Copyright © 2011-2022 走看看