Vue: How to change a value of state and use it in other page and change page structure at starting by it? - vue.js

In this project, we can login from login.vue by clicking login button and if it is success then we can see Lnb.vue in dashboard.vue
I thought if i code like this then pageSso will be 1 when I check the checkbox in login.vue in Lnb.vue then it will not show only "Account" menu.
When I used console.log(pageSso) at mounted cycle it showed pageSso was 0. What would be the problem?
store/store.js
export const state = () => ({
pageSso: 0,
})
export const getters = {
pageSso: (state) => state.pageSso,
}
export const mutations = {
setPageSso(state, data) {
console.log('mutations setPageSso data', data)
state.pageSso = data
}
}
export const actions = {
setPageSso({
commit
}, data) {
console.log('actions setPageSso data', data)
commit('setPageSso', data)
},
}
pages/login.vue
<template>
<input
class="checkbox_sso"
type="checkbox"
v-model="sso"
true-value="1"
false-value="0" >SSO checkbox
<button class="point" #click="submit">login</button>
</template>
<script>
export default {
data() {
return {
sso: '',
}
},
computed: {},
methods: {
submit() {
this.$store.dispatch('store/setPageSso', this.sso)
//this.$store.dispatch('store/login', data)
},
</script>
pages/dashboard.vue
<template>
<div class="base flex">
<Lnb />
<div class="main">
<Gnb />
<nuxt-child />
</div>
</div>
</template>
<script>
import Lnb from '#/components/Lnb'
import Gnb from '#/components/Gnb'
export default {
components: {
Lnb,
Gnb
},
mounted() {},
}
</script>
components/Lnb.vue
<template>
<ul>
<li :class="{ active: navbarState == 7 ? true : false }">
<a href="/dashboard/settings">
<img src="../assets/images/ico_settings.svg" alt="icon" /> Settings
</a>
</li>
<li v-show="pageSso != 1" :class="{ active: navbarState == 8 ? true : false }">
<a href="/dashboard/user">
<img src="../assets/images/ico_user.svg" alt="icon" />
Account
</a>
</li>
</ul>
</template>
<script>
import {
mapState
} from 'vuex'
export default {
data() {
return {}
},
computed: {
...mapState('store', {
// navbarState: (state) => state.navbarState,
pageSso: (state) => state.pageSso,
}),
},
mounted() {
console.log('pageSso ->', this.pageSso);
},
methods: {
},
}
</script>

Your console.log(pageSso) logs 0 because the mounted hook of Lnb.vue happens once, and it happens when the component is inserted into the DOM.
You insert Lnb into the DOM unconditionally in this line of dashboard.vue:
<Lnb />
and this is roughly when it's mounted hook is triggered.
Your pageSso seems to be changed only after you triggered the submit() method, which — I guess — happens way later, when you submit the login form.
Your Lnb.vue currently is always mounted. If you don't want to show it until pageSso is equal to 1, add a v-if on it in dashboard.vue like this:
<Lnb v-if="pageSso === 1" />
You currently don't have pageSso variable in dashboard.vue, you must take it from the store.
N.B.: Mind the difference between v-show and v-if directives: v-show only hides the component with display: none; while v-if actually removes or inserts the component from/to the DOM. With v-show, the component gets mounted even if you don't see it. With v-if, the component's mounted hook will fire each time the condition evaluates to true.

Related

how to send click button's value to a props

In my parent component I have a button and child component:
<div> #click="editMe(edit)" />
<edit-team :openModal="openModal"/>
</div>
export default {
data() {
return {
openModal: false,
};
},
method: {
editMe(edit) {
this.openModal = true;
},
}
}
So after I click the editMe button, I am expecting openModal becomes true and goes true to child component.
<template>
<el-dialog
:visible.sync="modal"
/>
</template>
<script>
export default {
props: {
openModal: {
type: Boolean,
required: true,
},
},
data() {
return {
modal: this.openModal,
};
},
</script>
But unfortunately, the modal is not opening because props comes as false always. I assigned openModal to new variable because it was giving me a warning about mutating props. So how do you think I can send the props in right value?
In child just try this
<template>
<el-dialog
:visible.sync="openModal"
/>
</template>
<script>
export default {
props: {
openModal: {
type: Boolean,
required: true,
},
},
},
</script>
If you have sibilngs components and you need to retrieve data, you can use the emit keyword and emit events
Then it will work like this :
The sibling emit the event to show the modal
The parent update the showModalData to true
This child is re-rendered
Vue.component('modal', {
template: '#modal',
props: ['show'],
});
Vue.component('buttonModal', {
template: '#buttonModal',
methods: {
showModal(){
this.$emit('show-modal-button', true)
}
}
});
new Vue({
el: '#app',
data: () => ({
showModalData: false
}),
methods: {
editMe() {
this.showModalData = true
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>
<div id="app">
<p>this is the parent</p>
<hr>
<button-modal #show-modal-button="editMe">Show modal</button-modal>
<hr>
<modal :show="showModalData" />
</div>
<template id="modal">
<div>
props show : {{ show }}
<h2 v-if="show">This is the modal</h2>
</div>
</template>
<template id="buttonModal">
<div>
<p>This is the sibilng</p>
<button #click="showModal"> Show the modal through sibiling components </button>
</div>
</template>

Vue3 objects from Array only rendering after making a small change in component

ers,
Experiencing a strange rendering issue. I am grabbing user data from localForage located in my Vuex store in a promise in the following component:
<template>
<div>
<h1>Users available for test {{ $route.params.id }}</h1>
<v-form>
<div v-if="this.import_complete">
<UserList
:users="users"
/>
</div>
</v-form>
</div>
</template>
<script>
import UserList from './UserList.vue';
export default {
name: 'UserManagement',
components: {
UserList,
},
data: () => ({
users: [],
import_complete: false,
}),
mounted() {
Promise.resolve(this.$store.getters.getUsersByTestId(
this.$route.params.testId,
)).then((value) => {
this.users = value;
this.import_complete = true;
});
},
};
</script>
Since it's a promise, I am setting a boolean import_complete to true, and a div in the template is only passing through the data as a prop when this boolean is true
Next, I am consuming the data in another template, in a for loop.
<template>
<div>
<v-container>
<v-banner v-for="user in this.users" :key="user.index">
{{ user.index }} {{ user.name }} {{ user.profile }}
<template v-slot:actions>
<router-link
:to="`/usering/${user.test}/user/${user.index}`">
<v-btn text color="primary">Open usering analysis</v-btn>
</router-link>
<v-btn text color="warning" #click="deleteUser(user.index)">Delete</v-btn>
</template>
</v-banner>
</v-container>
</div>
</template>
<script>
export default {
name: 'UserList',
props: {
users: Object,
},
methods: {
deleteUser(index) {
this.$store.dispatch('delete_user', index);
},
},
mounted() {
console.log('mounted user list, here come the users');
console.log(this.users);
},
};
</script>
The thing is, the first time it doesn't show anything. Only when I make a tiny change in the last component (can be an Enter followed by a save command) and suddenly the users are displayed on the page.
Interestingly, in the first scenario, the user's array is already filled, I see it in the console (created in the mount method) as well in the Chrome developer Vue tab.
It's probably some kind of Vue thing I am missing? Does someone have a clue?
[edit]
I've changed the code to this, so directly invoking the localForage. It seems to work, but I would still like to understand why the other code won't work.
this.test = this.$store.getters.getTestByTestId(this.$route.params.testId);
this.test.store.iterate((value, key) => {
if (key === (`user${this.$route.params.userId}`)) {
this.user = value;
}
}).then(() => {
this.dataReady = true;
}).catch((err) => {
// This code runs if there were any errors
console.log(err);
});

Vue: Toggle Button with Data from Child to Parent

I have a parent component that has numerous containers. Each container has an image and some buttons.
I have over simplified the parent and child components below. When a button is clicked that is within the child component, I would like to toggle the class on an element that is in the parent container. I would like to effect each image individually, not globally. How do I do this?
parent:
<template>
<div>
<div :class="{ active: mock }">
<img src="/path">
</div>
<toggleButtons/>
</div>
<div>
<div :class="{ active: mock }">
<img src="/path">
</div>
<toggleButtons/>
</div>
</template>
<script>
import toggleButtons from './toggleButtons'
export default {
name: "parent",
components: {
toggleButtons
}
};
</script>
child:
<template>
<div class="switch-type">
<a #click="mock = false">Proto</a>
<a #click="mock = true">Mock</a>
</div>
</template>
<script>
export default {
name: "toggleButtons",
data() {
return {
mock: false
}
}
};
</script>
Oversimplified example of how you can pass data from child to parent:
Child:
<a #click="$emit('mockUpdated', false)">Proto</a>
<a #click="$emit('mockUpdated', true)">Mock</a>
Parent (template):
<toggleButtons #mockUpdated="doSomething" />
Parent(methods):
doSomething(value) {
// value will be equal to the second argument you provided to $emit in child
}
EDIT: (toggling the class for each individual container):
I would probably create a new component for the container (container.vue), pass a path as a prop :
<template>
<div>
<div :class="{ active: mock }">
<img :src="path">
</div>
<toggleButtons #mockUpdated="doSomething" />
</div>
</template>
<script>
export default {
props: {
path: String,
},
data() {
return {
mock: false
}
},
methods: {
doSomething(value) {
this.mock = value;
}
}
}
</script>
and then in Parent.vue, you can import the container component and use it like:
<template>
<Container path="/path-to-file.jpg" />
<Container path="/path-to-file.jpg" />
</template>
There is nothing to do with slots in your case. You need "emit event" to parent from button, and pass mock data to update img states. Slot is a very different thing. There are multiple ways to achive your goal. One way can be something like this:
parent
<AppImage v-for="img in imageData" :key="img.id" :image="img"/>
data() {
iamges: ["yourPath1", "yourPath2"]
},
computed: {
imageData() {
// adding ID is almost always a good idea while creating Vue apps.
return this.images.map(x => {
id: Math.floor(Math.random() * 1000),
path: x
})
}
}
Image.vue
<img :path="image.path" :class={ active: mock} />
<toggleButtons #toggled=changeImageState />
props: [image],
data() {
mock: ''
},
methods: {
changeImageState(event) {
this.mock = event
}
}
ToggleButtons.vue
<a #click="toggleMock(false)">Proto</a>
<a #click="toggleMock(true)">Mock</a>
emits: ['toggled']
methods: {
toggleMock(val) {
this.$emits('toggled', val)
}
}
Please read the code and let me know if you have any question.

Vue Mounting Component removing div

I am trying to mount a component on a function, it works fine. However I've got it setup so that it destroys the div after X amount of seconds. Then when I try and add the compoent again its removed the base div. I'm not sure how to fix this though...
Component:
<template>
<div>
<b-alert show dismissible variant="danger">
<i class="mdi mdi-block-helper mr-2"></i>{{ text }}
</b-alert>
</div>
</template>
<script>
export default {
name: "alertDanager",
props: {
text: null
},
created() {
setTimeout(() => this.destoryEl(), 5000);
},
methods: {
destoryEl() {
this.$destroy();
this.$el.parentNode.removeChild(this.$el);
}
}
};
</script>
Spawning the component in
const DangerAlertExtended = Vue.extend(dangerAlert);
const error = new DangerAlertExtended({ propsData: { text: "Error message" } });
error.$mount("#error");
I'm not sure how to make it stop overwriting the #error div...
Why not let v-if exclude it from the DOM instead of removing the element? Alternatively, it could be hidden but remain in the DOM with v-show (that's probably what I would do, unless there's a specific reason you need for it to not be in the DOM). I think it's generally better to let Vue manage the DOM rather than manipulate yourself.
<template>
<div v-if="showAlert">
<b-alert show dismissible variant="danger">
<i class="mdi mdi-block-helper mr-2"></i>{{ text }}
</b-alert>
</div>
</template>
<script>
export default {
name: "alertDanager",
props: {
text: null,
showAlert: true
},
created() {
setTimeout(() => this.hideAlert(), 5000);
},
methods: {
hideAlert() {
this.showAlert = false
}
}
}
</script>

How can I reset dropdown data if modal closed on vue component?

My case like this
I have two component, parent and child component
My parent component like this :
<template>
...
<div class="row">
...
<location-select level="continentList" type="1"/>
...
<location-select level="countryList" type="2"/>
...
<location-select level="cityList" type="3"/>
...
</div>
</template>
<script>
...
export default{
...
}
</script>
The parent component is a modal bootstrap
My child component like this :
<template>
<select class="form-control" v-model="selected" #change="changeLocation">
<option value="0" disabled>Select</option>
<template v-for="option in options">
<option v-bind:value="option.id" >{{ option.name }}</option>
</template>
</select>
</template>
<script>
...
export default{
props: ['level','type'],
data() { return { selected: '' };},
computed:{
...mapGetters([
'getContinentList', 'getCountryList','getCityList'
]),
options(){
const n = ['getContinentList', 'getCountryList','getCityList']
return this[n[this.type-1]]
}
},
methods:{
...mapActions([
'getLocationList'
]),
changeLocation(event){
if(this.type==1){
this.getLocationList([{type:2},{level:'countryList'}])
this.getLocationList([{type:3},{level:'cityList'}])
}else if(this.type==2){
this.getLocationList([{type:3},{level:'cityList'}])
}
}
},
created() {
if(this.type==1)
this.getLocationList([{type:1},{level:'continentList'}])
if(this.type==2 && this.selected!='')
this.getLocationList([{type:2},{level:'countryList'}])
if(this.type==3 && this.selected!='')
this.getLocationList([{type:3},{level:'cityList'}])
},
mounted() {
$(this.$parent.$refs.modal).on('hidden.bs.modal', (e) => {
Object.assign(this.$data, this.$options.data())
})
},
};
</script>
If the modal show, I select continent, country and city. Then I close the modal
After that I show the modal again. Then I select country and city first, the data is still exist
I want to reset the data. So if I open modal again, before I choose continent, country and city data is not showing
I try :
Object.assign(this.$data, this.$options.data())
and this :
Object.assign(this.$data,this.$options.data.call(this))
and this too :
this.$forceUpdate()
when modal hidden
But, it does not work
Seems it must update data computed:{...}. But I'm still confused to do it
How can I solve this problem?
Have you tried reseting the selected data attribute in mounted lifecycle hook?
...
mounted() {
let $vm = this;
$(this.$parent.$refs.modal).on('hidden.bs.modal', (e) => {
$vm.selected = '';
});
},
...
Just v-if the modal component and it will rerender/recalculate everything when toggled.
Parent of Parent component:
<template>
<div class="parent-of-parent">
<your-modal-component v-if="isModalOpened" #close="closeModal"></your-modal-component>
</div>
</template>
<script>
export default{
data() {
return { isModalOpened: false };
},
methods: {
openModal() {
this.isModalOpened = true;
}, // method to open it
closeModal() {
this.isModalOpened = false;
}, // method to attach to emit event from modal on close
},
};
</script>
Be sure to attach click event on the icon you click for close or whatever.
And attach a method to the event which emits like this.
this.$emit('closeModal');
If you have problem animating the modal use <transition>
<transition name="fadeIn">
<your-modal-component v-if="isModalOpened" #close="closeModal"></your-modal-component>
</transition>