How to use custom object methods with Vuex? - javascript

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?

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,
};
},
};

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 mapState in js files?

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.

Watcher Vue JS on window object

I want to store some of the variables between components in global window object, so I do window.showFilters = !window.showFilters
In the components, I am trying to use watcher on window object like
watch: {
"window.showFilters": {
handler: () => {
console.log(window.showFilters);
},
deep: true
}
},
However, this doesn't work so I have to use Vuex which I would like to use only for business data rather just code variables.
Is there are a right way to watch for variables in the window object?
If you do not want to use the Vuex store (which is the recommended way - and you can simply separate your business and application state in 2 different Vuex modules) then you are advised to store such variables in the root Vue instance (the one in your main.js)
The problem with global variables (a.k.a window properties) is that they are not reactive. You could try to use this.$set(window, 'showFilters', true) but this is ugly and might not work.
But even putting your variables inside the root Vue instance you still need to inform your components about the changed value - and you can do this by emitting events only (a watcher can only watch for changes inside the same component - not between components)
I resolved like this:
mounted(){
setInterval(()=>app.myownwatcher(), 100)
},
methods: {
myownwatcher(){
// do something with window.showFilters
}
}
It does not the best way but work :/ When my app run, I create a interval who update my model

Vue2 passing arbitrary named variable as prop

I am new to Vue and after checking the docs I can not figure out how to achieve the following:
pass an arbitrarily named variable as a prop to a component instance.
From my understanding, props are meant to be a way to allow data to be passed to a component and as it states on the website:
Passing Data to Child Components with Props:
Props are custom attributes you can register on a component. When a value is passed to a prop attribute, it becomes a property on that component instance.
Since props can be required, it would seem that we can design components under the assumption that some data would be there, and possible within certain parameters (if the validator option is specified).
So I would like to define a function or object outside of vue, e.g. in an application, and pass this function or object to my vue instance.
This works if my named object of function has the exact same name as the prop to which I attempt to bind it. However, as I might have multiple instances of the Vue component and I might want to bind different data, I find using the same name for the variable less than ideal.
Now if I do as the Vue warning suggests, and name object / function the same as the prop, then the warning switches to that my data is not defined inside vue and to make sure it is reactive by reading: https://v2.vuejs.org/v2/guide/components-props.html
which, to be honest, doesnt really explain how to solve the issue,
or move the prop to the data level.
Which I can do (still gives the same warning), but kind of defeats the purpose of having props with my understanding of Vue.
This become more frustrating with anonymous vue instances.
e.g.
<script>
export default {
props: {
// records: {
// default: function(){return{}},
// type: Object
// }
},
data: function() {
return {
records: {} // define even an empty value in data for it to be 'reactive'
}
},
computed: {
fields: function() {
},
keys: function() {
return Object.keys(this.records)
}
},
methods: {
}
}
</script>
trying to use this as a component and set records to var myRecords = {"a": {}} fails:
<my-comp :records="myRecords"/>
So how exactly should I circumvent this? Where should I define my data then? and how should I handle the naming in the case of multiple instances?
A more fledged on example is found on a similar question:
Vue2: passing function as prop triggers warning that prop is already set
So I would like to define a function or object outside of vue, e.g. in an application, and pass this function or object to my vue instance.
It's hard to give a definitive answer because I don't know the specifics of how you have organized your code. Are you using Webpack? Single file components (.vue)? If yes to any of these, then you needn't use global variables in the way you have described in your question.
Your entire Vue app should consist of a single root Vue instance (which you instantiate with new Vue(...), and from there each component is rendered within the root component's template, and templates of those components, and so on.
Looking at the following template:
<my-comp :records="myRecords"/>
myRecords must be a property on the Vue component instance whose template contains the above. It could be declared within the data block, or as a computed property, or a prop, it doesn't matter.
Here's a small example:
<div id="app">
<my-comp :records="myRecords"></my-comp>
</div>
// Obtain records in some way and store it in a global variable
var records = ...
// This is the root Vue instance
new Vue({
el: '#app',
data: {
// You must store the records array in the Vue component like this
// for it to be referenced within the template.
// You can optionally transform the data first if you want.
myRecords: records.filter(r => r.name.startsWith('Bob'))
// ^ ^
// | |
// | +--- the global variable
// |
// +---- the name of the property on the component instance
}
})
Note that MyComp component does not access the records global variable in any way, it only takes its input through the records prop.

Categories

Resources