前端学习之路记录之巧建store.js

1,638 阅读1分钟

有时为了防止数据在组件中传来传去,会使用VUEX的store仓库,集中的去管理某一项数据,但是有时使用VUEX的成本较高,这时候就需要我们自己去新建了一个store文件,去集中的管理数据。具体的store.js代码如下:

// 首先建立一个store对象,然后在store对象里面建立state变量和setStore函数
const store = {
    state: {
        modalAData: {
            a: '可设置默认值',
            title: "可这只默认值"
        },
        modalBData: {

        },
        modalCData: {
          a: 0
        },
        List: [],
        num: 0,
        time:0,
        Id: ''
    },
    setStore: function (key, value) {
        if (typeof value === 'undefined') {
            return;
        };
        if (typeof value === 'string' || typeof value === 'number') {
            this.state[key] = value;
        } else if (Array.isArray(value)) {
            this.state[key] = value;
        } else {
            Object.keys(value).map(item => {
                if (value[item] != undefined) {
                    this.state[key][item] = value[item];
                }
            })
        }
    }
},
export default store;

如何使用?
在要使用store.js的文件中引入该文件

import $store from '@/js/store.js'; 具体位置根据自己项目而定

父组件中使用:

export default {
  data() {
    return {
      store: $store.state
    };
  },
}
$store.setStore('time', 5);
$store.setStore('ID', '3434');
$store.setStore('modalAData', {
          a: '数据替换',
          title: '数据替换'
    });

获取store.js中的变量

假设在子组件中获取父组件的传值,可在父组件中使用$store.setStore改变store,然后在子组件中使用
export default {
  data() {
    return {
      store: $store.state
    };
  },
  props: {
      modalAData: {
      type: Object,
      default: function() {
        return $store.state.modalAData;
      }
    }
  },
  created() {
     
  }
}

(本文仅供自己学习记录)