Vue3 组合 API 重构计算 favoritesRecipes

Vue3 composition API refactor computed favoritesRecipes

我是 vue3 组合 API 的新手。我已经创建了那个计算 属性 并且我想将该计算变量放在不同的文件中,我不确定我是否应该创建一个新组件或者我可以从一个 js 文件中实现它。 这是工作的组件(我用 setup() 做到了):

export default {
  name: "Recipes",
  setup() {
    const state = reactive({
      recipes: [],
      sortBy: "alphabetically",
      ascending: true,
      searchValue: "",
    });
    const favoritesRecipes = computed(() => {
      let tempFavs = state.recipes;
      // Show only favorites
      if (state.heart) {
        tempFavs = tempFavs.filter(item => {
          return item.favorite;
        });
      }
      return tempFavs;
    ...
    });
    ...
  }
  return {
    ...toRefs(state),
    favoriteRecipes
    }
// end of setup
}

你可以把它分成两个文件

state.js

export const state = reactive({
  recipes: [],
  sortBy: "alphabetically",
  ascending: true,
  searchValue: "",
});

export const favoriteRecipes = computed(() => {
  let tempFavs = state.recipes;
  // Show only favorites
  if (state.heart) {
    tempFavs = tempFavs.filter(item => {
      return item.favorite;
    });
  }
  return tempFavs;
})

recipes.vue

import { state, favoriteRecipes } from "state.js";
export default {
  name: "Recipes",
  setup() {
    return {
      ...toRefs(state),
      favoriteRecipes,
    };
  },
};

但这会使状态持久化,因此如果您有多个组件,它们都将具有相同的 favoriteRecipesstate 值。


如果您希望它们对于每个组件都是唯一的...

state.js

export const withState = () => {
  const state = reactive({
    recipes: [],
    sortBy: "alphabetically",
    ascending: true,
    searchValue: "",
  });

  const favoriteRecipes = computed(() => {
    let tempFavs = state.recipes;
    // Show only favorites
    if (state.heart) {
      tempFavs = tempFavs.filter((item) => {
        return item.favorite;
      });
    }
    return tempFavs;
  });

  return { state, favoriteRecipes };
};

recipes.vue

import { withState } from "state.js";
export default {
  name: "Recipes",
  setup() {
    const {state, favoriteRecipes} = withState()
    return {
      ...toRefs(state),
      favoriteRecipes,
    };
  },
};