mobxjs / mobx-vue-lite

Lightweight Vue 3 bindings for MobX based on Composition API.
MIT License
69 stars 3 forks source link

Can ObserverComponent be compatible with Vue 2? #133

Open withoutmeat opened 6 months ago

withoutmeat commented 6 months ago

My component library is written using vue-demi and supports both Vue 2 and 3. Now, I want to make it reusable in React as well. I'm considering switching to MobX for writing the logic. However, I found that useLocalObservable from mobx-vue-lite seems to support Vue 2 and 3, but it doesn't support the following code structure.

import { makeAutoObservable } from 'mobx';

export class TodoStore {
  todos: { id: number; name: string }[] = [];

  constructor() {
    makeAutoObservable(this);
  }

  get filteredTodos() {
    return this.todos.filter(todo => todo.id > 2);
  }

  add() {
    this.todos.push({
      id: this.todos.length,
      name: uuid.v4(),
    });
  }

  delete(id: number) {
    const index = this.todos.findIndex(todo => todo.id === id);
    if (index > -1) {
      this.todos.splice(index, 1);
    }
  }
}

I can use it like this in Vue 3, but currently, the code is not working in Vue 2. Is it possible to make it compatible with Vue 2? I apologize for asking this question after explicitly mentioning that mobx-vue supports Vue 2. I am still looking forward to receiving a response. Thank you.

<template>
  <Observer>
    <button @click="() => todoStore.add()">add</button>
    <div class="todo" v-for="todo in todoStore.todos" :key="todo.id">
      {{ todo.id }}
      <button @click="todoStore.delete(todo.id)">delete</button>
    </div>
  </Observer>
</template>

<script lang="ts">
import { defineComponent } from 'vue-demi';
import { Observer } from 'mobx-vue-lite';
import { TodoStore } from '@dft/vision-renderless';

export default defineComponent({
  components: {
    Observer,
  },
  setup() {
    return {
      todoStore: new TodoStore(),
    };
  },
});
</script>