How to access store data in mounted function in vuex - javascript

I am having one root component know as App.vue. and another component named as FileUploaderParent.vue. I am calling a dispatch promise to store the data in the store. I am calling dispatch under mounted lifecycle hook.
On the other side, I am trying to access stored user data in the mounted function of a different component. It shows the error of undefined
I know, a work around can be to call same dispatch promise on the mounted function. But, It feels like a hack and the dispatch call is getting redundant.
Here is the code for App.vue:
<template>
<v-app>
<v-navigation-drawer v-model="drawer" app temporary >
<v-img :aspect-ratio="16/9" src="https://image.freepik.com/free-vector/spot-light-background_1284-4685.jpg">
<v-layout pa-2 column fill-height class="lightbox gray--text">
<v-spacer></v-spacer>
<v-flex shrink>
<!-- <div class="subheading">{{this.$store.getters.userData.name}}</div> -->
<!-- <div class="body-1">{{this.$store.getters.userData.email}}</div> -->
</v-flex>
</v-layout>
</v-img>
<v-list>
<template v-for="(item, index) in items">
<v-list-tile :href="item.href" :to="{name: item.href}" :key="index">
<v-list-tile-action>
<v-icon light v-html="item.icon"></v-icon>
</v-list-tile-action>
<v-list-tile-content>
<v-list-tile-title v-html="item.title"></v-list-tile-title>
</v-list-tile-content>
</v-list-tile>
</template>
</v-list>
</v-navigation-drawer>
<v-toolbar color="white" light :fixed=true>
<v-toolbar-side-icon #click.stop="drawer = !drawer"></v-toolbar-side-icon>
<v-img :src="require('#/assets/mad_logo.png')" max-width="80px" max-height="41px" />
<v-toolbar-title class="black--text justify-center" > <h1>MeshApp</h1></v-toolbar-title>
<v-spacer></v-spacer>
<v-avatar color="primary">
<!-- <span class="white--text headline">{{this.avatar.slice(0,2)}}</span> -->
</v-avatar>
</v-toolbar>
<v-content style="margin-top: 60px;">
<v-fade-transition mode="out-in">
<router-view></router-view>
</v-fade-transition>
</v-content>
</v-app>
</template>
<script>
export default {
name: 'app',
components: {
},
data() {
return {
avatar: '',
drawer: false,
items: [
{
href: 'home',
router: true,
title: 'home',
icon: 'grid_on',
},
{
href: 'view_volunteers',
router: true,
title: 'View Volunteer',
icon: 'group'
},
{
href: 'profile',
router: true,
title: 'profile',
icon: 'account_circle',
},
{
href: 'logout',
router: true,
title: 'Logout',
icon: 'toggle_off',
}
]
}
},
props: [],
mounted() {
this.$store.dispatch('getUserData').
then(() => {
let findAvatar = this.$store.getters.userData.name.split(" ")
let createAvatar = ''
for(let i = 0; i < findAvatar.length; i++) {
createAvatar = createAvatar + findAvatar[i].slice(0,1)
}
this.avatar = createAvatar
console.log(this.avatar)
// this.$store.dispatch('getUserId', id)
})
}
}
</script>
<style scoped>
v-content {
margin-top: 60px !important;
}
</style>
Here is the code for FileUploaderParent.vue:
<template>
<v-layout class="text-xs-center ">
<v-flex>
<image-input v-model="avatar">
<div slot="activator">
<v-avatar color = "primary" size="150px" v-ripple v-if="!avatar" class=" mb-3">
<h1 class="white--text"><span>{{this.defaultAvatar}}</span></h1>
</v-avatar>
<v-avatar size="150px" v-ripple v-else class="mb-3">
<img :src="avatar.imageURL" alt="avatar">
</v-avatar>
</div>
</image-input>
<v-slide-x-transition>
<div v-if="avatar && saved == false">
<!-- Stores the Image and changes the loader -->
<v-btn class="primary" #click="uploadImage" :loading="saving">Save Avatar</v-btn>
</div>
</v-slide-x-transition>
</v-flex>
</v-layout>
</template>
<script>
import ImageInput from './FileUploaderChild.vue'
export default {
name: 'app',
data () {
return {
defaultAvatar: '',
avatar: null,
saving: false,
saved: false
}
},
mounted() {
this.$store.dispatch('getUserData').
then(() => {
let findAvatar = this.$store.getters.userData.name.split(" ")
let createAvatar = ''
for(let i = 0; i < findAvatar.length; i++) {
createAvatar = createAvatar + findAvatar[i].slice(0,1)
}
this.defaultAvatar = createAvatar
})
},
components: {
ImageInput: ImageInput
},
watch:{
avatar: {
handler: function() {
this.saved = false
},
deep: true
}
},
methods: {
uploadImage() {
this.saving = true
setTimeout(() => this.savedAvatar(), 1000)
},
savedAvatar() {
this.saving = false
this.saved = true
}
}
}
</script>
<style>
</style>
This is how the store looks like:
store.js
actions: {
getUserData(context) {
return new Promise((resolve, reject) => {
axios.get('http://someurl.in/api/v1/users/'+this.state.userId, {
headers: {
'Content-Type': 'application/json'
},
auth: {
username: 'someusername',
password: 'pass'
}
}).
then(response => {
context.commit('storeUserData', response.data.data.users)
resolve(response); // Let the calling function know that http is done. You may send some data back
}).catch(error => {
reject(error);
})
})
}
},
mutations: {
storeUserData(state, data) {
state.userData = data
}
}
This is how the error looks like:
How do i access store data in FileUploaderParent.vue under mounted function?

The code you have written seems right, but if you still need an answer you can use watch on store
this.$store.watch(() => this.$store.state.userData, async () => {
//do your code here
});

How about adding a check that determines if an API call is required:
actions: {
getUserData(context) {
return new Promise((resolve, reject) => {
// Be sure to set the default value to `undefined` under the `state` object.
if (typeof this.state.userData === 'undefined') {
axios
.get('http://someurl.in/api/v1/users/' + this.state.userId, {
headers: {
'Content-Type': 'application/json'
},
auth: {
username: 'someusername',
password: 'pass'
}
})
.then(response => {
context.commit('storeUserData', response.data.data.users);
resolve(response.data.data.users);
})
.catch(error => {
reject(error);
});
}
else {
resolve(this.state.userData);
}
})
}
}

The this.$store.getters refers to a getter in your Vuex store. You have no getters in your Vuex store - at least none can be seen in your sample. (https://vuex.vuejs.org/guide/getters.html)

Related

How to correctly pass paramters to vuex mapActions

I have a ProjectPage.vue page that displays issues in a v-data-table. Projects are retrieved from a server api call in the sidebar and displayed there. After I choose a project, I would like to use that project's id to get its issues from the server. Is it possible to do so using Vuex.
Is it possible using Vuex, that each project can use the same .js file to retreive its issues, since there could be any number of projects.
What I am trying to do is from VerticalNavMenu.vue, pass an id and project as props to ProjectPage, so I can pass the id as a parameter to mapAction inside ProjectPage to retreive its issues.
The I'm way doing it now is not working. The table has no data available when I open a project's table
I hope Peoject_Pages.js helps understand what I'm asking about.
VerticalNavMenu.vue (related template lines are 38 -> 48)
<template>
<v-navigation-drawer
:value="isDrawerOpen"
app
expand-on-hover
mini-variant-width="60px"
floating
width="260"
class="app-navigation-menu"
:right="$vuetify.rtl"
#input="val => $emit('update:is-drawer-open', val)"
>
<!-- Navigation Header -->
<div class="vertical-nav-header d-flex items-center ps-6 pe-5 pt-5 pb-2">
<router-link to="/" class="d-flex align-center text-decoration-none">
<v-slide-x-transition>
<h2 class="app-title text--primary">ITrackerHub</h2>
</v-slide-x-transition>
</router-link>
</div>
<!-- Navigation Items -->
<v-list expand shaped class="vertical-nav-menu-items pr-5">
<nav-menu-link
title="Dashboard"
:to="{ name: 'dashboard' }"
:icon="icons.mdiHomeOutline"
></nav-menu-link>
<v-list>
<v-list-group :prepend-icon="icons.mdiTelevisionGuide">
<template v-slot:activator>
<v-list-item-content>
<v-list-item-title v-text="'My Projects'"></v-list-item-title>
</v-list-item-content>
</template>
<v-list-item v-for="(project, index) in ProjectList" :key="index">
<v-icon class="mx-2">{{ icons.mdiAccountGroup }}</v-icon>
<v-list-item-content>
<router-link
class="d-flex align-center text-decoration-none black--text"
:to="{ name: 'ProjectPage', params: { id: project.id, project} }"
>
{{ project.title }}
</router-link>
</v-list-item-content>
</v-list-item>
</v-list-group>
</v-list>
<nav-menu-link title="My Issues" :to="{ name: 'MyIssues' }" :icon="icons.mdiBookEditOutline"></nav-menu-link>
<nav-menu-link
style="position:relative; top:70px;"
title="Account Settings"
:to="{ name: 'pages-account-settings' }"
:icon="icons.mdiAccountCogOutline"
></nav-menu-link>
<nav-menu-link
style="position: relative; top: 200px"
title="Create Project"
:to="{ name: 'CreateProject' }"
:icon="icons.mdiPlusMinus"
></nav-menu-link>
</v-list>
</v-navigation-drawer>
</template>
<script>
// eslint-disable-next-line object-curly-newline
import {
mdiHomeOutline,
mdiAlphaTBoxOutline,
mdiEyeOutline,
mdiCreditCardOutline,
mdiTable,
mdiFileOutline,
mdiFormSelect,
mdiAccountCogOutline,
mdiAccountGroup,
mdiAccountMultiple,
mdiTelevisionGuide,
mdiBookEditOutline,
mdiPlusMinus,
} from '#mdi/js'
// import NavMenuSectionTitle from './components/NavMenuSectionTitle.vue'
import NavMenuGroup from './components/NavMenuGroup.vue'
import NavMenuLink from './components/NavMenuLink.vue'
import { mapGetters, mapActions } from 'vuex'
export default {
components: {
// NavMenuSectionTitle,
NavMenuGroup,
NavMenuLink,
},
computed: {
...mapGetters(['ProjectList'])
},
methods: {
...mapActions(['fetchProjects'])
},
created() {
// this.getProjectList()
this.fetchProjects()
},
props: {
isDrawerOpen: {
type: Boolean,
default: null,
},
},
setup() {
return {
icons: {
mdiHomeOutline,
mdiAlphaTBoxOutline,
mdiEyeOutline,
mdiCreditCardOutline,
mdiTable,
mdiFileOutline,
mdiFormSelect,
mdiAccountCogOutline,
mdiAccountGroup,
mdiAccountMultiple,
mdiTelevisionGuide,
mdiBookEditOutline,
mdiPlusMinus,
},
}
},
}
</script>
<style lang="scss" scoped>
.app-title {
font-size: 1.25rem;
font-weight: 700;
font-stretch: normal;
font-style: normal;
line-height: normal;
letter-spacing: 0.3px;
}
// ? Adjust this `translateX` value to keep logo in center when vertical nav menu is collapsed (Value depends on your logo)
.app-logo {
transition: all 0.18s ease-in-out;
.v-navigation-drawer--mini-variant & {
transform: translateX(-10px);
}
}
#include theme(app-navigation-menu) using ($material) {
background-color: map-deep-get($material, 'background');
}
.app-navigation-menu {
.v-list-item {
&.vertical-nav-menu-link {
::v-deep .v-list-item__icon {
.v-icon {
transition: none !important;
}
}
}
}
}
</style>
NavBar.js
import axios from 'axios'
const state = {
Projects: [],
}
const getters = {
ProjectList: (state) => state.Projects
}
const actions = {
async fetchProjects({ commit }) {
const response = await axios.get('https://fadiserver.herokuapp.com/api/v1/my-projects/')
commit('setProjects', response.data)
}
}
const mutations = {
setProjects: (state, Projects) => (state.Projects = Projects)
}
export default {
state,
getters,
actions,
mutations
}
ProjectPage.vue
<template>
<v-card>
<v-card-title class="text-center justify-center py-6">
<h1 class="font-weight-bold text-h2 basil--text">
{{ project.title }}
</h1>
</v-card-title>
<v-tabs v-model="tab" background-color="primary" dark centered>
<v-tab v-for="item in items" :key="item.tab">{{ item.tab }}</v-tab>
</v-tabs>
<v-tabs-items v-model="tab">
<v-tab-item v-for="item in items" :key="item.tab">
<v-card flat>
<v-card v-if="item.tab == 'Issues'">
<template>
<div class="text-center">
<v-dialog v-model="dialog" width="500">
<template v-slot:activator="{ on }">
<v-btn class="success" dark v-on="on">
<v-icon align-self: left>
mdi-plus-thick
</v-icon>
Add Issue
</v-btn>
</template>
<v-card>
<v-card-title>
<h2>Add Issue</h2>
</v-card-title>
<v-card-text>
<v-form class="px-3">
<v-text-field v-model="title" label="Title"></v-text-field>
<v-textarea v-model="description" label="Description"></v-textarea>
<v-select
item-text="text"
item-value="value"
:items="time_est"
v-model="time_estimate"
label="Time Estimate"
></v-select>
<v-select
item-text="title"
item-value="id"
:items="issueType"
v-model="issue_type"
label="Issue Type"
></v-select>
<v-select
item-text="title"
item-value="id"
v-model="issue_status"
label="Issue Status"
:items="issueStatus"
></v-select>
<v-select
item-text="title"
item-value="id"
:items="issueSeverity"
v-model="issue_severity"
label="Issue Severity"
></v-select>
<v-spacer></v-spacer>
<v-btn
flat
#click="
postIssue()
reloadPage()
"
class="success mx-0 mt-3"
>
<v-icon align-self:left>mdi-content-save-check-outline</v-icon> Save</v-btn
>
</v-form>
</v-card-text>
</v-card>
</v-dialog>
</div>
</template>
<v-card>
<v-data-table
:headers="headers"
:items="Project_Issues"
item-key="full_name"
class="table-rounded"
hide-default-footer
enable-sort
#click:row="handleClick"
>
</v-data-table>
</v-card>
</v-card>
</v-card>
</v-tab-item>
</v-tabs-items>
</v-card>
</template>
<script>
import axios from 'axios'
import { mapGetters, mapActions } from 'vuex'
export default {
props: ['id', 'project'],
computed: {
...mapGetters(['Project_Issues']),
},
data() {
return {
tab: null,
items: [{ tab: 'Issues' }, { tab: 'Calender' }, { tab: 'About' }],
title: '',
description: '',
time_estimate: '',
issue_type: '',
issue_status: '',
issue_severity: '',
time_est: [
{ value: '1', text: '1' },
{ value: '2', text: '2' },
{ value: '3', text: '3' },
{ value: '4', text: '4' },
{ value: '5', text: '5' },
{ value: '6', text: '6' },
{ value: '7', text: '7' },
{ value: '8', text: '8' },
],
}
},
setup() {
return {
headers: [
{ text: 'Title', value: 'title' },
{ text: 'Description', value: 'description' },
{ text: 'Estimate', value: 'time_estimate' },
{ text: 'Assignees', value: 'user' },
{ text: 'Type', value: 'issueType' },
{ text: 'Status', value: 'issueStatus' },
{ text: 'Severity', value: 'issueSeverity' },
],
}
},
methods: {
...mapActions(['fetchProjectIssueList']),
handleClick(issue) {
this.$router.push({
name: 'IssuePage',
params: { id: issue.id, issue },
})
},
postIssue() {
axios
.post('https://fadiserver.herokuapp.com/api/v1/my-issues/', {
title: this.title,
description: this.description,
time_estimate: this.time_estimate,
userid: 'f3260d22-8b5b-4c40-be1e-d93ba732c576',
projectid: this.id,
issueTypeId: this.issue_type,
issueStatusId: this.issue_status,
issueSeverityId: this.issue_severity,
})
.then(response => {
console.log(response)
})
.catch(error => {
console.log(error)
})
},
reloadPage() {
window.location.reload()
},
},
mounted() {
this.fetchProjectIssueList(this.id)
},
}
</script>
<style scoped>
.v-btn {
left: 43%;
}
</style>
Project_Page.js
import axios from 'axios'
const state = {
issuesList: [],
}
const getters = {
Project_Issues: (state) => state.issuesList
}
const actions = {
async fetchProjectIssueList({ commit }, {projectid}) {
const response = await axios.get('https://fadiserver.herokuapp.com/api/v1/my-issues-titles/?projectid=' + projectid)
commit('setProjectIssues', response.data)
},
}
const mutations = {
setProjectIssues: (state, issuesList) => (state.issuesList = issuesList)
}
export default {
state,
getters,
actions,
mutations
}
There are 2 ways of solving your problem.
Or you pass an object with the key projectid in the fetchProjectIssueList method
Or you do not need to destructure the object in the fetchProjectIssueList method
this.fetchProjectIssueList({ projectid: this.id })
...
async fetchProjectIssueList({ commit }, {projectid}) { ... }
or
this.fetchProjectIssueList(this.id)
...
async fetchProjectIssueList({ commit }, projectid) { ... }

I am learning vue, why I click the edit button of the parent component, the child component dialog box is not displayed?

I have changed the value of dialogVisible to true, but the dialog box just doesn't display
I modified the dialogVisible value of the subcomponent to true through ref, and passed the ID of each piece of data through props. I think there is nothing wrong with what I did. Originally, I wanted to implement the modification function, but now I can’t even display the dialog box. Can someone help me?
parent component
<template>
<div>
<NavMenu></NavMenu>
<listQuery></listQuery>
<DialogAddAffairsType></DialogAddAffairsType>
<el-table :data="tableData" stripe fit class="el-table" :header-cell-style="{background:'#f5f7fa',color:'#606266'}">
<el-table-column prop="id" label="ID" width="180">
</el-table-column>
<el-table-column prop="typename" label="类型名称" width="180">
</el-table-column>
<el-table-column prop="createdAt" label="创建时间">
</el-table-column>
<el-table-column label="操作">
<template slot-scope="scope">
<el-button size="mini" #click="handleEdit(scope.row.id)">编辑(edit)</el-button>
<el-button size="mini" type="danger" #click="handleDelete(scope.row.id, scope.$index)">删除</el-button>
</template>
</el-table-column>
</el-table>
<!-- 前组件后数据 -->
<editAffairsType :editAffairsType="affairsTypeId" ref="editAffairsType"></editAffairsType>
<Pager></Pager>
</div>
</template>
<script>
import axios from "axios";
import ListQuery from "#/components/ListQuery/index.vue";
import DialogAddAffairsType from "#/components/DialogAddAffairsType/index.vue";
import Pager from "#/components/Pager/index.vue";
import NavMenu from "#/components/NavMenu/index.vue";
import editAffairsType from "#/components/DialogAffairsType/index.vue";
export default {
name: 'AffairsTypeList',
components: {
ListQuery,
DialogAddAffairsType,
Pager,
NavMenu,
editAffairsType,
},
methods: {
getAllAffairsTypes() {
axios({
method: 'GET',
url: 'http://localhost:8080/api/affairsType/allAffairsTypes'
}).then(response => {
const data = response.data;
console.log("是否取到数据", data);
this.tableData = data;
})
},
handleDelete(id, index) {
this.$confirm("永久删除该事务类型, 是否继续?", "提示", {
confirmButtonText: "确定",
cancelButtonText: "取消",
type: "warning"
})
.then(() => {
axios({
method: 'DELETE',
url: 'http://localhost:8080/api/affairsType/deleteById',
params: {
id: id
}
}).then(response => {
if (response.status == 200) {
this.tableData.splice(index, 1);
}
})
this.$message({
type: "success",
message: "删除成功!"
});
})
.catch(() => {
this.$message({
type: "info",
message: "已取消删除"
});
});
},
handleEdit(id) {
this.affairsTypeId = id;
this.$refs.editAffairsType.dialogVisible = true;
console.log("数据准备成功")
console.log(this.change[0])
return this.affairsTypeId;
}
},
// 在实例创建完成后被立即同步调用(https://cn.vuejs.org/v2/api/#created)
created() {
this.getAllAffairsTypes();
},
data() {
return {
tableData: [],
affairsTypeId: "",
}
}
}
</script>
<style>
.el-table {
margin: 0 auto;
}
</style>
child component
<template>
<div>
<el-dialog title="修改事务类型" :visible.sync="dialogVisible" width="35%">
<span>
<el-form :model="AffairsType" :label-position="labelPosition" label-width="auto">
<el-form-item label="类型名称" required>
<el-input v-model="AffairsType.typename" :placeholder="placeholder.typename" style="width:50%"></el-input>
</el-form-item>
</el-form>
</span>
<span slot="footer">
<el-button #click="dialogVisible = false">取 消</el-button>
<el-button type="primary" #click="dialogVisible = false">确 定</el-button>
</span>
</el-dialog>
</div>
</template>
<script>
export default {
name: "editAffairsType",
// https://www.bilibili.com/video/BV1Zy4y1K7SH?p=66
props: {
affairsTypeId:{
// type:Number,
// required:true,
}
},
data() {
return {
dialogVisible: false,
}
},
methods: {
// change() {
// this.dialogVisible = this.changeAffairsType.dialogVisible;
// },
},
created(){
},
}
</script>
<style>
</style>

$emit functions inside promise

I've got a problem with event orders, I have one method for getting data and another to open modal with data from previous method, and it works fine, but modal is rendered before getting data, so I see previous result for a sec. I do understand that I need my methods to be called in promise, but fail to realize how to do this.
App.vue
<v-app>
<v-main>
<h1 class="text-center text-uppercase">Gallery</h1>
<Cards
:images="images"
#addImage="updateImage($event)"
#showModal="showPopup($event)"
/>
<Card :image="image" v-if="modal" #closeImage="toggleImage($event)" />
</v-main>
</v-app>
</template>
<script>
import Cards from "./components/Cards.vue";
import Card from "./components/Card.vue";
export default {
name: "App",
components: { Cards, Card },
data: () => ({
images: {},
image: {},
modal: false,
}),
methods: {
updateImage: function (updatedImage) {
this.image = updatedImage;
},
showPopup: function (state) {
this.modal = state;
},
toggleImage: function (state) {
this.modal = state;
},
},
};
</script>
Cards.vue
<v-row>
<v-col
v-for="image in images"
:key="image.id"
class="d-flex"
cols="4"
#click="
getImage(image.id);
toggleWindow();
"
>
<v-img :src="image.url" :id="image.id">
<template v-slot:placeholder>
<v-row class="fill-height ma-0" align="center" justify="center">
<v-progress-circular
indeterminate
color="grey lighten-5"
></v-progress-circular>
</v-row>
</template>
</v-img>
</v-col>
</v-row>
</template>
<script>
export default {
name: "Cards",
props: ["images"],
methods: {
getImage(imageId) {
fetch(`https://boiling-refuge-66454.herokuapp.com/images/${imageId}`)
.then((res) => {
if (res.status == 200) {
return res.json();
} else {
throw new Error(res.status);
}
})
.then((data) => {
this.$emit("addImage", data);
});
},
toggleWindow() {
let toggle = true;
this.$emit("showModal", toggle);
},
},
};
</script>
<style></style>
I believe this is because getImage() is an async method. It should return an Promise that resolves itself after the last then(). The last then is the one containing this.$emit("addImage", data);.
In your #click you should then wait for getImage() to be resolved before calling toggleWindow().
So something like #click="async () => { await getImage(image.id); toggleWindow();}".

Vue.js: Managing multiple buttons in Dropdown

I have the following Dropdown in a Vue.js Project.
<template>
<v-menu close-on-click transition="slide-y-transition">
<template v-slot:activator="{ on, attrs }">
<v-btn color="primary" v-bind="attrs" v-on="on">
Menu
</v-btn>
</template>
<v-list>
<v-list-item v-for="(item, index) in menuItemsMisc" :key="index">
<v-list-item-title>
<v-btn block color="white">{{ item.title }}</v-btn>
</v-list-item-title>
</v-list-item>
</v-list>
</v-menu>
</template>
<script>
export default {
name: 'MenuBar',
data: () => ({
menuItemsMisc: [
{ title: 'Visit Website' },
{ title: 'Logout' },
{ title: 'Purchase' },
]
}),
}
</script>
I want all these buttons to have different functions like:
Visit Website -> Link to a Website
Logout -> To Call a function
Purchase -> A Purchase Modal to appear
That's how I have been handling the drop-down buttons before using page routing.
<v-list-item v-for="(item, index) in menuItemsPages" :key="index">
<v-list-item-title>
<v-btn :to= "'/' + item.url" >{{ item.title }}</v-btn>
</v-list-item-title>
</v-list-item>
But I think Page routing isn't the best way to go if we have buttons Drastically different in functionality. How should I go about it?
(not vuetify)I am not sure if this is the best practice but you can try this:
In my router there is an About page and it works ! Also when we select other options I can see the outputs in console. If you can adapt this code into vuetify, it can work.
<template>
<div class="home">
<select v-model="selectedValue">
<template v-for="(item, index) in menuItemsMisc">
<option :value="item.title" :key="index"> {{item.title }} </option>
</template>
</select>
</div>
</template>
<script>
// # is an alias to /src
export default {
name: 'Home',
data() {
return {
selectedValue : "",
menuItemsMisc: [
{ title: 'Visit Website' },
{ title: 'Logout' },
{ title: 'Purchase' },
]
}
},
watch: {
"selectedValue": function() {
if (this.selectedValue === "Visit Website") {
this.$router.push({name: "About"})
}
else if (this.selectedValue === "Logout") {
this.doSomething()
}
else {
this.purchase()
}
}
},
methods: {
doSomething() {
console.log("I AM DOING SOMETHING")
},
purchase() {
console.log("hello purchase")
}
}
}
</script>
Another way is to define a function to the menuItemsMisc's elements, then pass it to #click of v-btn.
<template>
<v-menu close-on-click transition="slide-y-transition">
<template v-slot:activator="{ on, attrs }">
<v-btn color="primary" v-bind="attrs" v-on="on">Menu</v-btn>
</template>
<v-list>
<v-list-item v-for="(item, index) in menuItemsMisc" :key="index">
<v-list-item-title>
<!-- Pass `item.click` to `#click` -->
<v-btn block color="white" #click="item.click">{{ item.title }}</v-btn>
</v-list-item-title>
</v-list-item>
</v-list>
</v-menu>
</template>
export default {
name: "Home",
data: () => ({
menuItemsMisc: [
{
title: "Visit Website",
click: () => {
// Go to a route
this.$router.push({ name: "About" });
}
},
{
title: "Logout",
click: () => {
// Call a function
console.log("Logging out...");
}
},
{
title: "Purchase",
click: () => {
// Show modal
console.log("Showing purchase modal");
}
}
]
})
};
Here is a sample demo.
You can add a function to each object in your array like so :
menuItemsMisc: [
{ title: 'Visit Website', fn: () => { this.$router.push('/') }},
{ title: 'Logout' , fn: () => { /* Your logic */ }},
{ title: 'Purchase' , fn: () => { /* different logic */ }},
]
and use it with an event listener on click :
<v-btn #click="item.fn" >{{ item.title }}</v-btn>
A combination of both answers worked for me!
data: () => ({
menuItemsMisc: [
{ title: "Vorlage speichern" },
{ title: "Anwesenheit bearbeiten" },
],
)}
watch: {
selectedValue: function () {
if (this.selectedValue === "Vorlage speichern") {
this.saveAsVorlage(this.topListWithName);
} else if (this.selectedValue === "Anwesenheit bearbeiten") {
this.updateAnwesenheit = true;
}
},
},

Passing props from one step to another (steppers) in Vue

I am using steppers in vue. I am creating an agency in step 1 and on step 2 I am displaying the agency details. The issue is that the agency details don't appear on step 2 until I refresh page after going on step 2. Is there a way to pass agency as a prop from agency.vue to event.vue so that I dont need to refresh the page to make the agency details appear on step 2.
stepper.vue
<template>
<div >
<v-stepper v-model="e1">
<v-stepper-header>
<v-stepper-step :complete="e1 > 1" step="1">Agency</v-stepper-step>
<v-divider></v-divider>
<v-stepper-step :complete="e1 > 2" step="2">Event</v-stepper-step>
<v-divider></v-divider>
</v-stepper-header>
<v-stepper-items>
<v-stepper-content step="1">
<Agency #next="goTo(2, true)"></Agency>
</v-stepper-content>
<v-stepper-content step="2">
<Event/>
</v-stepper-content>
</v-stepper-items>
</v-stepper>
</div>
</template>
<script>
import Agency from 'parties/agency';
import Event from 'events/event';
export default {
components: {
Agency,
Event
},
data () {
return {
e1: 0,
agency: {
id: '',
name: '',
phone_number: ''
}
}
},
created() {
this.step = 1;
this.getAgency();
},
methods: {
getAgency() {
this.$axios.get('/agency.json')
.then(response => {
if (Object.keys(response.data).length > 0) {
this.agency = response.data;
}
})
},
goTo(step, can) {
if (can) {
this.e1 = step;
}
},
}
};
</script>
agency.vue
<template>
<v-card>
<v-form :model='agency'>
<v-layout row wrap>
<v-flex xs12 sm12 lg12 >
<v-layout row wrap>
<v-flex xs12 md6 class="add-col-padding-right">
<v-text-field
label='Agency Name'
v-model='agency.name'>
</v-text-field>
</v-flex>
</v-layout>
<v-layout row wrap>
<v-flex xs12 md6 class="add-col-padding-right">
<v-text-field
label='Agency Phone Number'
v-model='agency.phone_number'>
</v-text-field>
</v-flex>
</v-layout>
<v-layout row wrap>
<div>
<v-btn #click.prevent='saveAgency'>Save</v-btn>
</div>
</v-layout>
</v-flex>
</v-layout>
</v-form>
<v-btn #click.prevent='nextStep'>
Next
</v-btn>
</v-card>
</template>
<script>
export default {
data: function () {
return {
agency: {
id: '',
name: '',
phone_number: ''
}
};
},
created: function() {
this.getAgency();
},
methods: {
nextStep() {
this.$emit('next');
},
getAgency() {
this.$axios.get('/agency.json')
.then(response => {
if (Object.keys(response.data).length > 0) {
this.agency = response.data;
}
})
},
saveAgency() {
this.$axios.post('/agencies.json', { agency: this.agency })
.then(response => {
});
},
}
};
</script>
event.vue
<template>
<v-card class="mb-12">
<v-form :model='agency'>
{{ agency.name }}<br/>
{{ agency.phone_number }}<br/>
</v-form>
</v-card>
</template>
<script>
export default {
data: function () {
return {
agency: {
id: '',
name: '',
phone_number: ''
},
event_final: false
};
},
created: function() {
this.getAgency();
},
methods: {
getAgency() {
this.$axios.get('/agency.json')
.then(response => {
if (Object.keys(response.data).length > 0) {
this.agency = response.data;
if (this.agency.name === "XYZ") {
this.event_final = true;
}
}
}).
then(() => {
});
},
}
};
</script>
Have Agency emit the details in its next event, capture them at the parent and pass them as a prop to Event.
Given you load the initial data in stepper.vue, you can also pass that into Agency for editing
For example
// agency.vue
props: { editAgency: Object },
data () {
return { agency: this.editAgency } // initialise with prop data
},
methods: {
nextStep() {
this.$emit('next', { ...this.agency }) // using spread to break references
},
// etc, no need for getAgency() here though
}
<!-- stepper.vue -->
<Agency :edit-agency="agency" #next="nextAgency"></Agency>
<!-- snip -->
<Event :agency="agency" />
// stepper.vue
methods: {
nextAgency (agency) {
this.agency = agency
this.goTo(2, true)
},
// event.vue
export default {
props: { agency: Object } // no need for a local "data" copy of agency, just use the prop
}

Categories