Skip to content

Files

Latest commit

 

History

History
52 lines (40 loc) · 1.59 KB

useState.md

File metadata and controls

52 lines (40 loc) · 1.59 KB

useState

You need to use a plugin before using this hook.

Vue hook for mapState.

Usage

import { createComponent, computed } from '@vue/composition-api';
import { useState } from '@u3u/vue-hooks';

const Demo = createComponent({
  setup() {
    const state = {
      ...useState(['count']),
      ...useState('test', { count2: 'count' }),
    };

    const plusOne = computed(() => state.count.value + 1);
    const minusOne = computed(() => state.count2.value - 1);

    return { ...state, plusOne, minusOne };
  },

  render() {
    const { count, count2, plusOne, minusOne } = this;
    return (
      <div>
        <div>count: {count}</div>
        <div>plusOne: {plusOne}</div>
        <div style={{ marginTop: '10px' }}>test/count: {count2}</div>
        <div>test/minusOne: {minusOne}</div>
      </div>
    );
  },
});

Reference

function useState(
  namespace?: string,
  map: Array<string> | Object<string | function>,
): Object<Ref<any>>;

The usage of the useState hook is exactly the same as the usage of mapState (the same parameters)
The only difference is that the return value of useState is the Ref<any> dictionary. For each item in the dictionary, you need to use .value to get its actual value.

Please refer to the documentation of mapState for details.