How to use mapState in js files? - javascript

I want to access my states from a .js file using mapState in Vue.js.
I've tried
import { mapState } from 'vuex';
const foo = {
...mapState(['axios']),
};
foo.axios.get('...');
but it doesn't work. The error is
TypeError: foo.axios.get is not a function
What should I do to achieve that?
I have searched for other questions, but they access from store.state. ... instead of using mapState which I want.

I'm not sure using mapState is a good idea as it's very much intended to be used as a way to create computed properties on a component.
However, it can be made to work like this:
const foo = {
$store: store,
...mapState(['axios'])
};
foo.axios().get('...');
You can see the implementation of mapState here:
https://github.com/vuejs/vuex/blob/dev/src/helpers.js#L7
Note that it relies on this.$store to get a reference to the store. On a component this will be injected automatically but for your object it needs adding manually.
The other thing to note is that I'm having to invoke axios() as a method. Computed properties on components are defined as functions but accessed as properties but that magic trick is performed internally by Vue. On a normal JavaScript object like this there is no such magic so we just have to call the function as a function. Other benefits of computed properties, such as the caching, will also be lost.

Related

How to have data shared between Vue3 single file component instances?

I don't need to pass data between a parent component to a child one or the opposite, I need something like php/c static variables.
I want my sfc (single file component) to have some data that is shared among all instances in in the page.
As far as I understand that's why in sfc we define data as a function
export default {
data(){
return {
// props here
};
}
}
while in page scripts we can define it as an object
const app = new Vue({
data: {
// props here
},
}
That's because since we can have multiple instances of a sfc in the page defining its data as a function make each instance to execute in and get its own data, while with page script we can have a singe instance.
I need to define some of my sfc data to be shared between component instances, while other data to be per-instance.
Is there a way to do this?
That depends on the data to be defined, its complexity, and purpose.
If these are 2 or 3 readonly variables, they can be set as global properties using Vue.prototype (Vue 2) or app.config.globalProperties (Vue 3). I'm not sure, because in your example you use Vue 2 syntax.
If the data should be reactive, you can set up a simple state management as explained in the Vue documentation: Simple state management.
If the data is more complex than that, the next step will be Vuex.
Following #Igor answer I looked after the simple state management and found the ref() method that creates reactive primitive values.
In my specific use case I needed to share among all the sfc instances just an array, so in my sfc I had:
const reactive_array = ref([]);
export default {
data() {
return {
shared_array: reactive_array,
};
},
};

What is the role and usage of the setup function provided by vue3's Composition API

I need to know the correct usage and the best practice of the setup function provided by vue3's Composition API.
I checked in my current project where developers actually use the setup function instead of creating the component with the traditional approach.
If it is just a design principle or improvement something then where we should apply these. I read the official documentation but instead, they didn't explain the concept, they just provided the list of arguments available in this function.
MyBook.vue
<template>
<span>Warning:- {{warning}}</span>
<button #click="warning = !warning">toggle</button>
</template>
<script>
import { ref } from 'vue'
export default {
props: ['warning'],
setup(props, context) {
const warning = ref(props.warning)
return {
warning,
}
},
}
</script>
<MyBook
:warning="true"
/>
As you can see above, I can't use the same name of a property to data attribute for a component but in the case of setup, we can do this and update the value. (as property should not change within component).
The Vue devtool is also showing the setup as a different category.
setup sets up an instance and returns properties that it should have. The purpose of Composition API, which setup is a part of, is to replace Options API, where an instance is determined by component options. So setup is the replacement for data, methods, computed, watch and lifecycle hooks.
As the reference explains, setup also replaces beforeCreate and created lifecycle hooks, the rest of hooks are set inside of it.
There is no conflict between data and props in setup function because props is accessible as setup parameter, i.e. warning and props.warning are accessible at the same time. In a template, they aren't and shouldn't be distinguished, they instance properties, the solution is to not allow name conflicts. They have been previously available with $data.warning and $props.warning magic keywords but their use wasn't encouraged. If warning value differs from a prop of the same name, and both should be available in a template, it should have a different name.

sveltejs - static properties on components

I have a scenario where I need to provide information to a component class such that downstream instantiations can make use of that info.
For instance:
import { AComponent } from 'AComponent.svelte'
...
AComponent.classInfo = {something: somedata}
And then, the component could access that information as in:
<script>
let something = AComponent.classInfo.something
</script>
There seemed to be some effort in providing this kind of functionality in V2 (I'm using 3) that was discussed in these issues: Support Component Static Method #480, which resulted in Added setup function which can supply static methods/properties. #572.
However, scanning the current docs reveals no such setup method. So, did this survive from V2 to 3 & if not, is there some way to do this?
You can define static properties that are not instance specific in the module script block
<script context="module">
export const someValue = 123
</script>
<script>
// Normal component stuff
</script>
and then import it directly from the component file:
import { someValue } from './MyComponent.svelte'
Note that this is a value shared among all instances of this component.
At least in version v3.32, it's not possible to define static properties in a Svelte Component. Only named exports are possible.
The only workaround I known is using a custom webpack loader/rollup plugin, and the implementation is never pretty.

How to get component instance in data section in vuejs template?

I have a component that has complex rendering logic.
I try to carry out this logic to helper classes, for simplifying.
To do this, in the data section (for reactivity), I create class references as follows:
export default {
data: () => ({
state: new InitialState(this),
query: new QueryController(this)
})
}
As I understand it, at this point the context of this is not yet defined.
So, I have two questions.
1) Is there a way to pass the this component context in the data section (without lifecycle hooks)?
2) Is the approach with references to external classes of vuejs philosophy contrary?
Component instance is already available when data function runs, this is one of reasons why it has been forced to be a function.
Due to how lexical this works with arrow functions, it's incorrect to use them to access dynamic this. It should be:
data() {
return {
state: new InitialState(this),
query: new QueryController(this)
};
})
The problem with InitialState(this) is that the entire component instance is passed instead of relevant data, this breaks the principle of least privilege.
Despite Vue isn't focused on OOP, there's nothing wrong with using classes. One of possible pitfalls is that classes may not play well with Vue reactivity because it puts restrictions on the implementation. Another pitfall is that classes cannot be serialized to JSON and back without additional measures, this introduces limitations to how application state can be handled.
As I understand it, at this point the context of this is not yet defined.
Only because of the way you've written the code. The component instance does exist and is available. It is sometimes used to access the values of props for determining the initial values of data properties.
For example, here is an example from the documentation:
https://v2.vuejs.org/v2/guide/components-props.html#One-Way-Data-Flow
export default {
props: ['initialCounter'],
data: function () {
return {
counter: this.initialCounter
}
}
}
The reason why your code doesn't work is because you are using an arrow function. If you change it to the following then this will be available:
export default {
data () {
return {
state: new InitialState(this),
query: new QueryController(this)
}
}
}
See also the note here:
https://v2.vuejs.org/v2/api/#data
Note that if you use an arrow function with the data property, this won’t be the component’s instance, but you can still access the instance as the function’s first argument
As to your other question about whether using classes like this is contrary to Vue...
I don't think the use of classes like this is encouraged but they can be made to work so long as you understand the limitations. If you have a clear understanding of how Vue reactivity works, especially the rewriting of properties, then it is possible to write classes like this and for them to work fine. The key is to ensure that any properties you want to be reactive are exposed as properties of the object so Vue can rewrite them.
If you don't need reactivity on these objects then don't put them in data. You'd be better off just creating properties within the created hook instead so the reactivity system doesn't waste time trying to add reactivity to them. So long as they are properties of the instance they will still be accessible in your templates, there's nothing special about using data from that perspective.
I think computed is a better way to do what you want
export default {
computed:{
state(){
return new InitialState(this);
},
query(){
return new QueryController(this);
}
}
}

How to use custom object methods with Vuex?

I have several custom js objects, where I encapsulated needle logic.
So, these objects don't have relation with vuex at all, something like that:
export default class Property {
constructor(object) {
// some logic
}
addChild(property) {
// some logic
}
}
Also, I have button in my vue component, which firing vue method:
methods: {
addItem() {
this.property.addChild();
},
},
And there is problem:
this.property - it is object from vuex store.
So, when I call method in such way, I get vue error:
Error: [vuex] Do not mutate vuex store state outside mutation handlers.
Yeah, I understand, what Vue wants.
But for me it is more clear to encapsulate some complex logic in needle objects. Also, I want to use vuex for global app state.
So, please, could you share experience how to deal with vuex and custom object methods?
If you want to use vuex you simply have to use mutation to alter it's states.
So, in the the Property object's addChild function,
where you would alter state, I assume you would do it like
Store.state.xxx = 'new'
Instead of doing that, you call mutation like
Store.commit('alterState')
There's not too much difference in terms of complexity, right?

Categories

Resources