简体   繁体   中英

Vue JS : Method Style Getter (to filtering) AND reactivity to state change

I worked on a simple schedule application and i use Vuex as a state manager.

I want a way to filter the task state, to only return specific date and category tasks (Method Style Getter ig?) but i also want the component which get these tasks (via Method Style Getter) to react (so rerender) every time the task state change.

What is the most effective way to get there?


Access the tasks

export default {
  name: "TasksContainer",
  methods: {
    logSomething() {
      console.log("new task (good)");
    },
  },
  components: {
    Task,
  },
  computed: {
    ...mapGetters(["weekCourseTasks", "courseTasks", "nowMoment"]),
  },
};

Update tasks

export default {
  name: "AddTask",
  data() {
    return {
      taskName: "",
      taskDetail: "",
      taskCourse: "",
      taskDate: "",
    };
  },
  methods: {
    ...mapActions(["addTask"]),
    postForm() {
      this.addTask({
        taskName: this.taskName,
        taskDetail: this.taskDetail,
        taskCourse: this.taskCourse,
        taskDate: this.taskDate,
      });

      this.$emit("new-task");
    },
  },
};

If I understand you correctly, you would like to have tasks, that you can filter based on the date and other categories. Vuex allows for such getter methods.

The following code block allows you to write getters based on parameters.

getters: {
// ...
  getTaskByDate: (state) => (date) => {
    return state.tasks.find(task => task.date === date)
  }
}

In order to see them:

store.getters.getTaskByDate(xyz);

This should allow you to filter your state and make the component responsive.

A full documentation can be found here under the part "Method-Style Access"

Additionally, be sure to perform your updates according to the guidelines to preserve reactivity.

Since a Vuex store's state is made reactive by Vue, when we mutate the state, Vue components observing the state will update automatically. This also means Vuex mutations are subject to the same reactivity caveats when working with plain Vue:

Prefer initializing your store's initial state with all desired fields upfront.

When adding new properties to an Object, you should either:

Use Vue.set(obj, 'newProp', 123), or

Replace that Object with a fresh one. For example, using the object spread syntax we can write it like this:

state.obj = { ...state.obj, newProp: 123 }

(From the Vuex mutations documentation )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM