How to use another computed property inside mounted or created hooks? - vue.js

This is my my code?
computed: {
posts() {
return this.$store.getters['posts/postsByUser']
},
loggedIn() {
return this.$store.getters['auth/check'];
},
user() {
return this.$store.getters['auth/user']
}
},
created() {
this.$store.dispatch('posts/fetchPostsByUser', this.user.id)
}
Please tell me if you need more clearance

Use this computed property (user) which is available on the Vue component instance
created() {
this.$store.dispatch('posts/fetchPostsByUser', this.user.id)
}

Related

watcher in vuejs not working for props value

I am working on vue app. The issue I am facing here is that I want to run a method if props has value and in my case manager value. So I am trying something like this but the debugger is not called in the watcher. Please help me find where I am going wrong.
<script>
export default {
props: ['manager'],
watch: {
manager: function (value) {
debugger
if(value) {
this.validationManager();
}
}
},
methods: {
validationManager(){
console.log("Hello")
}
}
};
</script>
We can definetely watch the props, please try this:
watch: {
manager: {
// the callback will be called immediately after the start of the observation
immediate: true,
handler (val, oldVal) {
//do your stuff here
this.validationManager();
}
}
}
You forget the deep attribute for watcher
watch: {
manager: {
handler(value){
if(value) {
this.validationManager();
}
},
immediate: true,
deep: true,
}
}

How do I make Vue 2 Provide / Inject API reactive?

I set up my code as follows, and I was able to update checkout_info in App.vue from the setter in SomeComponent.vue, but the getter in SomeComponent.vue is not reactive.
// App.vue
export default {
provide() {
return {
checkout_info: this.checkout_info,
updateCheckoutInfo: this.updateCheckoutInfo
}
},
data() {
return {
checkout_info: {},
}
},
methods: {
updateCheckoutInfo(key, value) {
this.checkout_info[key] = value
}
}
}
// SomeComponent.vue
export default {
inject: ['checkout_info', 'updateCheckoutInfo']
computed: {
deliveryAddress: {
get() { return this.checkout_info.delivery_address }, // <---- Not reactive??
set(value) { return this.updateCheckoutInfo('delivery_address', value) }
}
}
}
I found the answer after many hours of searching. You have to use Object.defineProperty to make it reactive. I'm not sure if this is the best approach, but this is a working example.
export default {
data() {
return {
checkout_info: {},
}
},
provide() {
const appData = {}
Object.defineProperty(appData, "checkout_info", {
enumerable: true,
get: () => this.checkout_info,
})
return {
updateCheckoutInfo: this.updateCheckoutInfo,
appData,
}
}
}
You can later access it via this.appData.checkout_info
This note from official documentation.
Note: the provide and inject bindings are NOT reactive. This is
intentional. However, if you pass down an observed object, properties
on that object do remain reactive.
I think this is the answer to your question.
source:
https://v2.vuejs.org/v2/api/#provide-inject
I would put the values in an object:
var Provider = {
provide() {
return {
my_data: this.my_data
};
},
data(){
const my_data = {
foo: '1',
fuu: '2'
};
return {
my_data;
}
}
}
var Child = {
inject: ['my_data'],
data(){
console.log(my_data.foo);
return {};
},
}
When are object properties they are reactive. I don't know if this is the correct solution but it works in my case.

Vue: Can watchers be used to watch a computed property?

I am trying to see if I can use a watcher method to look for a change in a computed property rather than watching the individual store properties here. Would that work or can they only be used on data properties and props?
computed: {
optionsTrue() {
return this.$store.getters.getOption1IsTrue && this.$store.getters.getOption2IsTrue
}
},
watch: {
optionsTrue(newVal) {
// would this work to check when the value of the computed property has changed or can watcher only watch data properties?
}
}
Working code
computed: {
completed: function () {
return this.required && this.textAnswer !== '';
},
},
watch: {
completed: function(val) {
console.log(val)
}
}

VueJS: Computed Property Is Calculated Before Created in Component?

I have a component, which looks like this:
export default {
name: 'todos',
props: ['id'],
created () {
this.fetchData()
},
data() {
return {
}
},
computed: {
todos () {
return this.$store.state.todos[this.id]
}
},
methods: {
async fetchData () {
if (!this.$store.state.todos.hasOwnProperty(this.id)) {
await this.$store.dispatch('getToDos', this.id)
}
}
}
}
This is what's happening:
The component receives an id via props.
When the component loads I need to fetch some data based on the id
I have a created() hook from where I call a function fetchData() to fetch the data.
In methods, the fetchData() function dispatches an action to get the data. This gets and stores the data in Vuex store.
The computed property todos gets the data for this id.
The problem is that when the page first loads, the computed property todos shows up as undefined. If I change the page (client side) then the computed property gets the correct data from the store and displays it.
I am unable to understand why computed property doesn't update?
You could use following approach:
component.vue (and just render todoItem)
methods: {
async fetchData () {
const _this = this;
if (!this.$store.state.todos.hasOwnProperty(this.id)) {
this.$store.dispatch('getToDos', {id: this.id, callback: () => {
_this.todoItem = _this.$store.state.todos[_this.id]
}});
}
}
}
store.js
actions: {
getToDos: (context, payload) => {
// simulate fetching externally
setTimeout(() => {
context.commit("getToDos__", {newId: payload.id, task: "whatever" });
payload.callback();
}, 2000);
},
Base on here
When this hooks is called, the following have been set up: reactive data, computed properties, methods, and watchers. However, the mounting phase has not been started, and the $el property will not be available yet.
I think what might solve it is if you create a getter for todos.
So in your VueX Store add:
getters: {
todos(state) {
return state.todos;
}
};
And than in your computed use:
computed: {
todos () {
return this.$store.getters.todos[this.id]
}
}

Vue computed syntax error with mapState

I have this code:
computed: {
mapState(["appErrors", "user", "profilesFor"]),
compiledData () {
return {
template: `<p>${this.data}</p>`
}
}
}
Basically I am using Vuex and it has mapState but I also want to define my own computed functions so I changed
computed: mapState(["appErrors", "user", "profilesFor"]) --Works
to
computed: {
mapState(["appErrors", "user", "profilesFor"]),
compiledData () {
return {
template: `<p>${this.data}</p>`
}
}
}
But it doesn't work. How would I fix this issue?
The mapState helper provides an object containing computed getter functions.
Use the spread operator to include each of those functions in your computed object:
computed: {
...mapState(["appErrors", "user", "profilesFor"]),
compiledData () {
return {
template: `<p>${this.data}</p>`
}
}
}