Answer the question
In order to leave comments, you need to log in
How to create a global variable in Vue3?
Hello!
I don’t understand a little how to solve this problem:
We need such a variable / function that would be available in any component.
That is, I got the current user, and I want to continue working with the data without requesting them again.
If you use vuex, then for each component you have to connect a global module - which, in general, is redundant, in my opinion, a beginner.
Answer the question
In order to leave comments, you need to log in
How to create a global variable in Vue3?
import {computed, ref} from "vue";
export const todos = ref([]);
export const activeTodos = computed(() => {
return todos.value.filter(todo => !todo.done);
});
let id = 0;
export function addTodo(name, done = false) {
todos.value.push({name, done, id: id++});
};
export function removeTodo(todo) {
todos.value = todos.value.filter(_todo => _todo.id !== todo.value.id);
};
export function toggleTodo(todo) {
todo.value.done = !todo.value.done;
};
export function clearTodos() {
todos.value = [];
};
<script setup>
import {computed, ref, onMounted} from "vue";
import Todo from "./Todo.vue";
import {todos, activeTodos, clearTodos, addTodo} from "./main.js";
const showAll = ref(true);
const selectedTodos = computed(() => {
return showAll.value ? todos.value : activeTodos.value;
});
function onEnter(event) {
addTodo(event.currentTarget.value);
event.currentTarget.value = "";
}
onMounted(() => {
addTodo("Task 01", true);
addTodo("Task 02");
addTodo("Task 03");
});
</script>
<script setup>
import {toRefs} from "vue";
import {toggleTodo, removeTodo} from "./main.js";
const props = defineProps(["todo"]);
const {todo} = toRefs(props);
function onClick() {
toggleTodo(todo);
}
function onRightClick() {
removeTodo(todo);
}
</script>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question