Vue3穷人商店

问题描述 投票:0回答:1

所以我尝试使用 vue 的组合 api 创建一个简单的商店,但无论我做什么,由于某种原因它都无法正常工作。

在 store.mjs 我有非常简单的代码:

export const testString = ref("abc");
export const testObject = reactive({ abc: 1, xyz: 2 });

问题是无论我在哪里导入它们,它们都没有反应。

我也尝试将它们包装在像 pinia 那样的函数中:

export default function useStore(){
   return { testString, testObject }
}
javascript vuejs3 vue-composition-api
1个回答
0
投票

这应该作为设置和访问

abc
值的
xyz
reactive
值的用例。

const { createApp, ref, reactive, watchEffect } = Vue;

const state = reactive({ abc: 1, xyz: 2 });
const testString = ref('My Title');

createApp({
  setup() {
    const handleAbcInput = () => {
      console.log("abc updated to: ", state.abc);
      if (isNaN(state.abc) || state.abc < 0) {
        state.abc = 0;
      }
    };
    const handleXyzInput = () => {
      console.log("xyz updated to: ", state.xyz);
      if (isNaN(state.xyz) || state.xyz < 0) {
        state.xyz = 0;
      }
    };

    watchEffect(() => {
      console.log("Current value of abc: ", state.abc);
    });
    watchEffect(() => {
      console.log("Current value of xyz: ", state.xyz);
    });

    return { testString, state, handleAbcInput, handleXyzInput };
  }
}).mount("#app");
<div id="app">
  <h1>{{ testString }}</h1>
  <p>({{ state.abc }}, {{ state.xyz }})</p>
  <input v-model="state.abc" @input="handleAbcInput">
  <input v-model="state.xyz" @input="handleXyzInput">
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/3.4.8/vue.global.min.js"></script>

您还可以计算值并处理验证:

const { createApp, ref, reactive, computed } = Vue;

const state = reactive({ abc: 1, xyz: 2 });
const testString = ref('My Title');
const validationMessage = ref('');

createApp({
  setup() {
    const validateInput = (value) => {
      const num = +value;
      if (isNaN(num)) {
        validationMessage.value = 'Input must be a number';
        return 0;
      }
      validationMessage.value = ''; // clear message on valid input
      return num;
    };
  
    const abc = computed({
      get() {
        return state.abc;
      },
      set(value) {
        state.abc = validateInput(value);
      }
    });

    const xyz = computed({
      get() {
        return state.xyz;
      },
      set(value) {
        state.xyz = validateInput(value);
      }
    });

    return { testString, abc, xyz, validationMessage };
  }
}).mount("#app");
.err-msg { color: red; }
<div id="app">
  <h1>{{ testString }}</h1>
  <p>({{ abc }}, {{ xyz }})</p>
  <input v-model="abc">
  <input v-model="xyz">
  <p class="err-msg" v-if="validationMessage">{{ validationMessage }}</p>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/3.4.8/vue.global.min.js"></script>

© www.soinside.com 2019 - 2024. All rights reserved.