Vue3 Composition API рефакторинг вычисленное избранное

Я новичок в API композиции с vue3. Я создал это вычисляемое свойство, и я хотел бы иметь эту вычисляемую переменную в другом файле, я не уверен, должен ли я создавать новый компонент или я могу получить его из файла 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
}

person Bernardao    schedule 03.03.2021    source источник


Ответы (1)


Вы можете разделить его на два файла

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,
    };
  },
};

Но это сделает состояние постоянным, поэтому, если у вас несколько компонентов, все они будут иметь одинаковые значения favoriteRecipes и state.


Если вы хотите, чтобы они были уникальными для каждого компонента ...

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,
    };
  },
};
person Daniel    schedule 03.03.2021