N
N
Nikolay2021-11-24 20:59:28
Vue.js
Nikolay, 2021-11-24 20:59:28

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

1 answer(s)
G
GrayHorse, 2021-11-25
@GrayHorse

How to create a global variable in Vue3?

Take and create. It's not Vue 2.
Or are you not using the Composition API and script setup ?
Declared what you need in regular .js files, then you use it in any .vue components, you just need to import it.
Actually live demo:
https://sfc.vuejs.org/#eyJBcHAudnVlIjoiPHRlbX...
main.js
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 = [];
};

app.vue
<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>

Todo.vue
<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 question

Ask a Question

731 491 924 answers to any question