How can I send data from parent to child component by vuex store in vue component? - vue.js

My parent component like this :
<template>
...
<search-result/>
...
</template>
<script>
import {mapActions} from 'vuex'
...
export default {
...
props: ['category'],
mounted() {
this.updateCategory(this.category)
},
methods: {
...mapActions(['updateCategory']),
}
}
</script>
My child component like this :
<template>
...
</template>
<script>
import {mapGetters} from 'vuex'
...
export default {
...
mounted() {
console.log(this.getCategory)
},
computed: {
...mapGetters(['getCategory'])
},
}
</script>
My modules vuex to send data between components like this :
import { set } from 'vue'
...
// initial state
const state = {
category: null
}
// getters
const getters = {
getCategory: state => state.category
}
// actions
const actions = {
updateCategory ({commit}, payload) {
commit(types.UPDATE_CATEGORY, payload)
}
}
// mutations
const mutations = {
[types.UPDATE_CATEGORY] (state, payload) {
state.category = payload
}
}
export default {
state,
getters,
actions,
mutations
}
I try like that, but it does not works
If the code executed, the result of console.log(this.getCategory) in the child component is null
For example category prop in the parent component = 7. Should the result of console.log(this.getCategory) in the child component = 7
Why it does not work? Why the result is null?
Note :
I can just send the category data via prop. But here I do not want to use prop. I want to send data via vuex store. So I want to set and get data only via vuex store

Child's mounted hook is executed before parent's mounted hook. ( why? See this link)
console.log(this.getCategory) happens before this.updateCategory(this.category).
Therefore, you get null in the console.
If you put console.log(this.getCategory) in updated hook, you would be getting the right value in the console later on.

Jacob goh has pointed out the problem.
To solve this issue you can make use of vm.$nextTick() in the child component's mounted hook to ensure that the entire view has been rendered and the parent's mounted hook is called.
<template>
...
</template>
<script>
import {mapGetters} from 'vuex'
...
export default {
...
mounted() {
this.$nextTick(() => {
console.log(this.getCategory);
})
},
computed: {
...mapGetters(['getCategory'])
},
}
</script>
Here is the working fiddle
You can learn more about why use vm.nextTick() here: Vue updates the DOM asynchronously

Related

Access component parameters inside caller component

I have a component which I call inside another component as:
COMPONENT 1
<template>
<FiltersComponent />
</template>
export default Vue.extend({
components: { FiltersComponent }
)}
So, this FiltersComponents have some parameters I want to access into my component one
COMPONENT 2 DATA
data() {
return {
TestList: [] as string[],
Test2List: null as string[] | null,
}
},
How can I access that TestList and Test2List inside COMPONENT 1?
There are multiple possibilities: If one component is a child component or sibling of the other, you might want to take a loop at props (passing data down) and events (passing data up). Otherwise, if they are not siblings or children, you can use a store like vuex.
To use the docs example:
vue entry point: (e.g., app.js):
import { createApp } from 'vue'
import { createStore } from 'vuex'
// Create a new store instance.
const store = createStore({
state () {
return {
someProperty: 'someValue'
}
},
mutations: {
update (state, value) {
state.someProperty = value
}
}
})
const app = createApp({ /* your root component */ })
// Install the store instance as a plugin
app.use(store)
In your component's script-section:
this.$store.commit('update', 'YOUR_VALUE')
Other component:
const val = this.$store.state.someProperty
However, this is only a very basic example. You should definitely check out the docs, especially the sections about state, getters and mutations.
Always store the state as high in the component tree as you need, meaning that if you need these lists inside component 1, store them there. Then, you can use props and events to access and update the data inside component 2.
Alternatively, you can use a centralized store like Vuex.
You can achieve the same using ref,
Check the below example
<template>
<FiltersComponent ref="childComponent" /> <!-- Adding ref over here -->
</template>
export default Vue.extend({
components: { FiltersComponent }
)}
then in any of your methods or mounted section in Component 1. You can access Component2 data like
this.$refs.childComponent.TestList
or
this.$refs.childComponent.Test2List
So simple isn't it? ;)

Watch child properties from parent component in vue 3

I'm wondering how I can observe child properties from the parent component in Vue 3 using the composition api (I'm working with the experimental script setup).
<template>//Child.vue
<button
#click="count++"
v-text="'count: ' + count"
/>
</template>
<script setup>
import { ref } from 'vue'
let count = ref(1)
</script>
<template>//Parent.vue
<p>parent: {{ count }}</p> //update me with a watcher
<Child ref="childComponent" />
</template>
<script setup>
import Child from './Child.vue'
import { onMounted, ref, watch } from 'vue'
const childComponent = ref(null)
let count = ref(0)
onMounted(() => {
watch(childComponent.count.value, (newVal, oldVal) => {
console.log(newVal, oldVal);
count.value = newVal
})
})
</script>
I want to understand how I can watch changes in the child component from the parent component. My not working solution is inspired by the Vue.js 2 Solution asked here. So I don't want to emit the count.value but just watch for changes.
Thank you!
The Bindings inside of <script setup> are "closed by default" as you can see here.
However you can explicitly expose certain refs.
For that you use useContext().expose({ ref1,ref2,ref3 })
So simply add this to Child.vue:
import { useContext } from 'vue'
useContext().expose({ count })
and then change the Watcher in Parent.vue to:
watch(() => childComponent.value.count, (newVal, oldVal) => {
console.log(newVal, oldVal);
count.value = newVal
})
And it works!
I've answered the Vue 2 Solution
and it works perfectly fine with Vue 3 if you don't use script setup or explicitly expose properties.
Here is the working code.
Child.vue
<template>
<button #click="count++">Increase</button>
</template>
<script>
import { ref } from 'vue';
export default {
setup() {
return {
count: ref(0),
};
},
};
</script>
Parent.vue
<template>
<div id="app">
<Child ref="childComponent" />
</div>
</template>
<script>
import { ref, onMounted, watch } from 'vue';
import Child from './components/Child.vue';
export default {
components: {
Child,
},
setup() {
const childComponent = ref(null);
onMounted(() => {
watch(
() => childComponent.value.count,
(newVal) => {
console.log({ newVal }) // runs when count changes
}
);
});
return { childComponent };
},
};
</script>
See it live on StackBlitz
Please keep reading
In the Vue 2 Solution I have described that we should use the mounted hook in order to be able to watch child properties.
In Vue 3 however, that's no longer an issue/limitation since the watcher has additional options like flush: 'post' which ensures that the element has been rendered.
Make sure to read the Docs: Watching Template Refs
When using script setup, the public instance of the component it's not exposed and thus, the Vue 2 solutions will not work.
In order to make it work you need to explicitly expose properties:
With script setup
import { ref } from 'vue'
const a = 1
const b = ref(2)
defineExpose({
a,
b
})
With Options API
export default {
expose: ['publicData', 'publicMethod'],
data() {
return {
publicData: 'foo',
privateData: 'bar'
}
},
methods: {
publicMethod() {
/* ... */
},
privateMethod() {
/* ... */
}
}
}
Note: If you define expose in Options API then only those properties will be exposed. The rest will not be accessible from template refs or $parent chains.

Vuex is resetting already set states

Have started to play around with Vuex and am a bit confused.
It triggers the action GET_RECRUITERS everytime I load the component company.vue thus also making an api-call.
For example if I open company.vue => navigate to the user/edit.vue with vue-router and them go back it will call the action/api again (The recruiters are saved in the store accordinly to Vue-dev-tools).
Please correct me if I'm wrong - It should not trigger the action/api and thus resetting the state if I go back to the page again, correct? Or have I missunderstood the intent of Vuex?
company.vue
<template>
<card>
<select>
<option v-for="recruiter in recruiters"
:value="recruiter.id">
{{ recruiter.name }}
</option>
</select>
</card>
</template>
<script>
import { mapGetters } from 'vuex'
export default {
middleware: 'auth',
mounted() {
this.$store.dispatch("company/GET_RECRUITERS")
},
computed: mapGetters({
recruiters: 'company/recruiters'
}),
}
</script>
company.js
import axios from 'axios'
// state
export const state = {
recruiters: [],
}
// getters
export const getters = {
recruiters: state => {
return state.recruiters
}
}
// actions
export const actions = {
GET_RECRUITERS(context) {
axios.get("api/recruiters")
.then((response) => {
console.log('API Action GET_RECRUITERS')
context.commit("GET_RECRUITERS", response.data.data)
})
.catch(() => { console.log("Error........") })
}
}
// mutations
export const mutations = {
GET_RECRUITERS(state, data) {
return state.recruiters = data
}
}
Thanks!
That's expected behavior, because a page component is created/mounted again each time you route back to it unless you cache it. Here are a few design patterns for this:
Load the data in App.vue which only runs once.
Or, check that the data isn't already loaded before making the API call:
// Testing that your `recruiters` getter has no length before loading data
mounted() {
if(!this.recruiters.length) {
this.$store.dispatch("company/GET_RECRUITERS");
}
}
Or, cache the page component so it's not recreated each time you route away and back. Do this by using the <keep-alive> component to wrap the <router-view>:
<keep-alive>
<router-view :key="$route.fullPath"></router-view>
</keep-alive>

How to use SocketIO event at different Vue components same time

I have 3 Components. App.vue, Header.vue and Example.vue
App.vue is my Parent component. Header.vue and Example.vue is my child components.
My Header.vue created() method :
created()
{
socket.on('notification', data => {
console.log('Header Page');
});
}
My Example.vue created() method :
created()
{
socket.on('notification', data => {
console.log('Example Page');
});
}
When page rendered, i see only "Example Page" at console.
Only the last event is triggered when the event has the same name.
This is simple example. I use Vue Router and use socket only App.vue. For different operations, i check router name. It is very diffucult and complicated.
I want use different operations with same event name at different components.
I want output like this :
Header Page
Example Page
It is possible by using mixins in Vue js
Just create a file mixin.js in src directory
mixin.js
const myMixin = (value) => {
return {
created(){
if (value) console.log(value);
}
}
}
export default myMixin;
In Header.vue import the mixin.js file
<script>
import myMixin from '../mixin.js';
export default {
name: 'header-component',
mixins: [myMixin("header page")],
};
</script>
In Example.vue import the mixin.js file
<script>
import myMixin from '../mixin.js';
export default {
name: 'example-component',
mixins: [myMixin("example page")],
};
</script>

Managing State for Overlay Dismissed Components in Vuetify

I'm building out a vuetify/nuxt frontend for the first time, and I've moved my v-navigation-drawer component out of the default.vue layout, and into it's own component, so that it can be reused in multiple layouts.
The activator for this drawer still remains in the default.vue component, so I added a sidebar state to vuex:
export const state = () => ({
baseurl: 'http://example.com/api/',
sidebar: false,
authenticated: false,
token: null,
user: null,
})
The mutator for the sidebar looks like so:
export const mutations = {
toggleSidebar(state) {
state.sidebar = !state.sidebar;
}
}
This works perfectly when opening the drawer, but because the drawer is dismissed via clicking the overlay, or clicking off of sidebar (if you've turned the overlay off) vuex throws a huge error:
How can I make this work correctly through vuex?
Instead of binding the drawer's model directly to $store.state.sidebar, use a computed setter in the drawer component. Note that you must pass in the new value from the drawer itself, don't just toggle whatever's already in the store.
<template>
<v-navigation-drawer v-model="drawer" ...>
</template>
<script>
export default {
computed: {
drawer: {
get () {
return this.$store.state.sidebar
},
set (val) {
this.$store.commit('sidebar', val)
}
}
}
}
</script>
// vuex mutation
sidebar (state, val) {
state.sidebar = val
}
https://v2.vuejs.org/v2/guide/computed.html#Computed-Setter
https://vuex.vuejs.org/en/forms.html
Another option is to bind the prop and event separately
<template>
<v-navigation-drawer :value="$store.state.sidebar" #input="$store.commit('sidebar', $event)" ...>
</template>
https://v2.vuejs.org/v2/guide/components.html#Using-v-model-on-Components
Another solution is to use vuex-map-fields package which enables two-way data binding for states saved in a Vuex store.
It makes the code clear, readable more than the normal way (as in the accepted answer).
Basic example:
in your store file
// Import the `getField` getter and the `updateField`
// mutation function from the `vuex-map-fields` module.
import { getField, updateField } from 'vuex-map-fields';
export const state = () => ({
baseurl: 'http://example.com/api/',
sidebar: false,
authenticated: false,
token: null,
user: null,
})
export const getters = {
// Add the `getField` getter to the
// `getters` of your Vuex store instance.
getField,
}
export const mutations = {
// Add the `updateField` mutation to the
// `mutations` of your Vuex store instance.
updateField,
}
in your component
template>
<v-navigation-drawer v-model="sidebar" ...>
</template>
<script>
import { mapFields } from 'vuex-map-fields';
export default {
computed: {
// The `mapFields` function takes an array of
// field names and generates corresponding
// computed properties with getter and setter
// functions for accessing the Vuex store.
...mapFields([
'baseurl',
'sidebar',
// etc...
]),
}
}
</script>
for more details, you can check its githab page