快速上手

一个基础的 Vue 应用示例,帮助你开始使用 TanStack vue-store。

App.vue

html
<script setup>
import Increment from './Increment.vue';
import Display from './Display.vue';
</script>

<template>
  <h1>你的朋友中有多少人喜欢猫或狗?</h1>
  <p>按下面的按钮来增加喜欢猫或狗的朋友数量。</p>
  <Increment animal="dogs" />
  <Display animal="dogs" />
  <Increment animal="cats" />
  <Display animal="cats" />
</template>
<script setup>
import Increment from './Increment.vue';
import Display from './Display.vue';
</script>

<template>
  <h1>你的朋友中有多少人喜欢猫或狗?</h1>
  <p>按下面的按钮来增加喜欢猫或狗的朋友数量。</p>
  <Increment animal="dogs" />
  <Display animal="dogs" />
  <Increment animal="cats" />
  <Display animal="cats" />
</template>

store.js

js
import { Store } from '@tanstack/vue-store';

// 你也可以在 Vue 组件外部实例化 store!
export const store = new Store({
  dogs: 0,
  cats: 0,
});

export function updateState(animal) {
  store.setState((state) => {
    return {
      ...state,
      [animal]: state[animal] + 1,
    };
  });
}
import { Store } from '@tanstack/vue-store';

// 你也可以在 Vue 组件外部实例化 store!
export const store = new Store({
  dogs: 0,
  cats: 0,
});

export function updateState(animal) {
  store.setState((state) => {
    return {
      ...state,
      [animal]: state[animal] + 1,
    };
  });
}

Display.vue

html
<script setup>
import { useStore } from '@tanstack/vue-store';
import { store } from './store';

const props = defineProps({ animal: String });
const count = useStore(store, (state) => state[props.animal]);
</script>

<!-- 仅当 `state[props.animal]` 变化时才会重新渲染。如果 store 中不相关的属性变化,则不会重新渲染 -->
<template>
  <div>{{ animal }}: {{ count }}</div>
</template>
<script setup>
import { useStore } from '@tanstack/vue-store';
import { store } from './store';

const props = defineProps({ animal: String });
const count = useStore(store, (state) => state[props.animal]);
</script>

<!-- 仅当 `state[props.animal]` 变化时才会重新渲染。如果 store 中不相关的属性变化,则不会重新渲染 -->
<template>
  <div>{{ animal }}: {{ count }}</div>
</template>

Increment.vue

html
<script setup>
import { store, updateState } from './store';

const props = defineProps({ animal: String });
</script>

<template>
  <button @click="updateState(animal)">我的朋友喜欢 {{ animal }}</button>
</template>
<script setup>
import { store, updateState } from './store';

const props = defineProps({ animal: String });
</script>

<template>
  <button @click="updateState(animal)">我的朋友喜欢 {{ animal }}</button>
</template>