Am from Angular2 whereby i was used to services and injection of services hence reusing functions how do i achieve the same in vuejs
eg:
I would like to create only one function to set and retrieve localstorage data.
so am doing it this way:
In my Login Component
this.$axios.post('login')
.then((res)=>{
localstorage.setItem('access-token', res.data.access_token);
})
Now in another component when sending a post request
export default{
methods:{
getvals(){
localstorage.getItem('access-token') //do stuff after retrieve
}
}
}
Thats just one example, Imagine what could happen when setting multiple localstorage items when retrieving one can type the wrong key.
How can i centralize functionality eg: setting token(in angular2 would be services)
There are a few different ways to share functionality between components in Vue, but I believe the most commonly used are either mixins or custom modules.
Mixins
Mixins are a way to define reusable functionality that can be injected into the component utilizing the mixin. Below is a simple example from the official Vue documentation:
// define a mixin object
var myMixin = {
created: function () {
this.hello()
},
methods: {
hello: function () {
console.log('hello from mixin!')
}
}
}
// define a component that uses this mixin
var Component = Vue.extend({
mixins: [myMixin]
})
var component = new Component() // => "hello from mixin!"
Custom module
If there are a lot of shared functionality with a logical grouping it might make sense to instead create a custom module, and import that where you need it (like how you inject a service in angular).
// localStorageHandler.js
const localStorageHandler = {
setToken (token) {
localStorage.setItem('access-token', token)
},
getToken () {
localstorage.getItem('access-token')
}
}
export default localStorageHandler
And then in your component:
// yourcomponent.vue
import localStorageHandler from 'localStorageHandler'
export default{
methods:{
getvals(){
const token = localStorageHandler.getToken()
}
}
}
Modules are using the more modern syntax of JavaScript, which is not supported in all browsers, hence require you to preprocess your code. If you are using the vue-cli webpack template it should work out of the box.
Related
How to access to current instance of application inside a component?
Option 1: Create a plugin
// define a plugin
const key = "__CURRENT_APP__"
export const ProvideAppPlugin = {
install(app, options) {
app.provide(key, app)
}
}
export function useCurrentApp() {
return inject(key)
}
// when create app use the plugin
createApp().use(ProvideAppPlugin)
// get app instance in Component.vue
const app = useCurrentApp()
return () => h(app.version)
Option 2: use the internal api getCurrentInstance
import { getCurrentInstance } from "vue"
export function useCurrentApp() {
return getCurrentInstance().appContext.app
}
// in Component.vue
const app = useCurrentApp()
In Vue.js version 3, you can access the current instance of an application inside a component using the getCurrentInstance() function provided by the Composition API.
Here's an example:
import { getCurrentInstance } from 'vue'
export default {
mounted() {
const app = getCurrentInstance()
console.log(app.appContext.app) // This will log the current instance of the application
}
}
Note that getCurrentInstance() should only be used in very specific situations where it's necessary to access the instance. In general, it's recommended to use the Composition API's reactive properties and methods to manage state and actions inside a component.
I know I can call the emit method from the setup method, but is there any way to emit event from any other functions without passing the emit method from setup method(not the the functions in the methods option, but a useXXX function) ?
setup function takes two arguments, First one is props.
And the second one is context which exposes three component properties, attrs, slots and emit.
You can access emit from context like:
export default {
setup(props, context) {
context.emit('event');
},
};
or
export default {
setup(props, { emit }) {
emit('event');
},
};
Source
in vue3 typescript setup
<script setup lang="ts">
const emit = defineEmits()
emit('type', 'data')
<script>
20220626
<script setup lang="ts">
const emit = defineEmits(['emit_a', 'emit_b'])
emit('emit_a')
emit('emit_b', 'emit_b_data')
<script>
With Vue 3 setup syntax sugar
<script setup lang="ts">
import { defineEmits } from 'vue'
const emit = defineEmits<{
(e: 'change', id: number): void
(e: 'update', value: string): void
}>()
function yourFunction (id: number) {
emit('change', id)
}
<script>
See docs: https://v3.vuejs.org/api/sfc-script-setup.html#typescript-only-features
Here's the proper way to emit events programmatically (using javascript) in vue3:
export default defineComponent({
// See: https://vuejs.org/guide/components/events.html#declaring-emitted-events=
emits: 'myEventName', // <--- don't forget to declare custom events emitted
setup(_, { emit }) {
emit('myEventName') // <--- emit custom event programmatically whenever we want
},
})
The emits function can just as easily be passed as a param to any function not declared inside setup.
Side-note regarding other answers: we should avoid using getCurrentInstance(), which was intended for library authors needing access to internals of vue components (a.k.a. this of vue v2), when there are better alternatives. Especially when those alternatives were designed explicitly for our use case.
methods: {
minhaFuncao(){
let data = "conteudo";
this.$emit("nomeDoMEuEvento", data);
}
}
SEE MORE AT :https://github.com/Carlos-Alexandre-Leutz/emitir-eventos-filho-pra-pai-com-dados-no-vue3
export const useEmit = () => {
const vm = getCurrentInstance()
const emitFactory = (event: string) => (...args: any[]) => vm.emit(event, ...args)
return {
emit: vm.emit,
emitModel: emitFactory('update:modelValue')
}
}
const useButtonHandlers = () => {
const { emit } = useEmit()
const onClick = () => emit('click')
return {
onClick
}
}
You can use getCurrentInstance from Vue. You can check it out in the docs.
Usage is like
function useFunctionThatEmitsSomething(){
const instance = getCurrentInstance();
// do something
instance.emit('event');
}
Edit: Even though this answer solves the author's problem, as per the linked docs, this method is intended only for ADVANCED use cases, e.g authoring a plugin or library. For common use cases, like building a simple SPA, using this is TOTALLY DISCOURAGED and should be avoided at all costs, since it can lead to unreadable and unmaintenable code. If you feel the need to use this in a case like that, you're probably doing something wrong.
I'm re-writing my old app using Quasar Framework which is based on Vue, and I have a piece of code (class) which encapsulates websocket functionality.
It is a fairly simple concept: user travels from page to page in the app, but if he receives a message he can see a toast message/reply or a counter of unread messages increments.
I'm a little bit lost in the Quasar (Vue) architecture and here is my question:
Where would I store a global object which communicates with outside world, exists as long as the application exists and accessible from anywhere?
I read documentation of Quasar (Vue) but I still don't know where to put it. Vuex doesn't look right since it is not a state of the app. It is more like a faceless component.
Does it mean that I should use a plugin or Vue.prototype or a global mixin or something else?
I appreciate if someone can share their experience and a piece of code describing how to initialize and access this object's methods.
in my opinion:
Method 1. Use quasar plugin base on Vue prototype (sure you knew it):
plugins/foo.js
const fooModule = {
a: 1,
doTest() { console.log('doTest') }
};
export default ({Vue}) => {
Vue.prototype.$foo = fooModule;
}
quasar.conf.js
plugins: [
'i18n',
'axios',
'foo',
],
component bar.vue:
methods: {
test () { this.$foo.doTest() }
}
Method 2. Just use js module
Because js module is singleton. Wherever you import a js module, it all points to the same pointer.
So just have GlobalTest.js:
export default {
a: 1,
inc() { this.a = this.a + 1 }
}
And test1.js:
import GlobalTest from '/path/to/GlobalTest'
console.log(GlobalTest.a); // output 1
console.log(GlobalTest.inc()); // inc
And test2.js:
import GlobalTest from '/path/to/GlobalTest'
console.log(GlobalTest.a); // Assuming this was called after test1.js: output 2
I used quasar cli but I just consider quasar as a UI lib.
--- Updated ---
It is a fairly simple concept: user travels from page to page in the app, but if he receives a message he can see a toast message/reply or a counter of unread messages increments.
Depend on the requirements, If you need "reactive" you should use Vuex (best built-in reactive lib) + split the app state into modules,
but I only use Vuex when I need "reactive" and avoid it when I just need to read & write the value.
// ~/store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
let store
export default function (/* { ssrContext } */) {
/* eslint-disable no-return-assign */
return store = new Vuex.Store({
modules: {...},
strict: process.env.DEV
})
}
export function ensureClientStoreExists () {
if (process.env.SERVER) {
return new Promise(() => { /* won't resolve */ })
}
if (process.env.CLIENT) {
if (store) {
return Promise.resolve(store)
}
return new Promise(resolve => {
setTimeout(resolve) // Avoid 'Maximum call stack size exceeded'
}).then(ensureClientStoreExists)
}
}
// Anywhere
import { ensureClientStoreExists } from '~/store/'
ensureClientStoreExists().then(store => {
console.log(store.state)
store.dispatch('XXX/YYY')
})
On my components I am having to access my endpoints (API Gateway/Lambda), this is currently requiring me to hardcode this on a per-component level. Obviously not ideal, haha.
Here is an example of what I have now on a Vue component:
async mounted() {
axios.get('https://XXXXXXX.execute-api.us-east-1.amazonaws.com/{environment}/{endpoint_name}')
.then(response => {
this.data = response.data;
})
}
Ideally I am trying to find an elegant way of populating these axios.get() sections, so I can have a main reference for the execution id and environment (dev/qa/prod/etc).
I am new to Vue.js, so I am struggling to find the ideal approach. Currently my thought would be to create string that pulls from main.js then adds onto the .get url. Such as .get(LAMBDA_URL + 'test'), ideas?
First of all, you can abstract away all api calls to their own file, somewhere in an api folder. You can then make your own get, post, put and delete methods that perform some basic boilerplate stuff like prepending the lambda url and parsing common things such as the status code.
You can go further by only calling these api endpoints in your vuex store if you have one. The nice part of that is that your components are no longer concerned where they get the data from. The implementation of getting the data is all in some fetch action somewhere in your store. Your components will use a getter to show things.
// api/index.js
import { apiUrl } from '#/config';
function apiRequest(method, url, data, whatever) {
return axios({
method,
data,
url: `${apiUrl}/${url}`
// etc
});
}
export function get(url, data, whatever) {
return apiRequest('get', url, data, whatever);
}
// etc
// Component
<template>
<div>
{{ data }}
</div>
</template>
<script>
import { mapGetters } from 'vuex';
export default {
name: 'my-component',
computed: {
...mapGetters({
data: 'animals/birds'
})
},
mounted () {
this.$store.dispatch('animals/fetchBirds');
}
}
</script>
Been reading the docs and googling around for best practice to handle api calls in bigger projects without luck (or ateast not what Im searching for).
I want to create a service / facade for the backend that I can load in every component that needs it. For exampel.
I want to fetch historical data for weather in a service so in every component I need this I can just load the weather-serivce and use a getter to fetch the wanted data. I would like to end up with something like below. But I dosent get it to work. So I wonder, what is best practice for this in vue.js?
import WeatherFacade from './data/WeatherFacade.vue'
export default {
name: 'Chart',
created () {
console.log(WeatherFacade.getWeather())
},
components: {
WeatherFacade
}
}
ps. using vue 2.1.10
It could be easily done by creating some external object that will hold those data and module bundling.What I usually do in my projects is that I create services directory and group them in order I want.
Let's break it down - services/WeatherFascade.js (using VueResource)
import Vue from 'vue'
export default {
getWeather() {
return Vue.http.get('api/weather')
}
}
If you have to pass some dynamic data such as ID, pass it as just parameter
import Vue from 'vue'
export default {
getWeather(id) {
return Vue.http.get(`api/weather/${id}`)
}
}
Then in your component you can import this service, pass parameters (if you have them) and got data back.
import WeatherFascade from '../services/WeatherFascade'
export default {
data() {
return {
weatherItems: []
}
},
created() {
this.getWeatherData()
},
methods: {
getWeatherData() {
WeatherFascade.getWather(// you can pass params here)
.then(response => this.weatherItems = response.data)
.catch(error => console.log(error))
}
}
}
You can use any library for that you like, for instance axios is cool.