我正在开发一个简单的应用程序,它在仪表板中显示了一个练习表。从那里,用户可以单击一个ExerciseItem并打开一个Exercise组件。我有Dashboard组件工作,但无法将数据传递给子练习组件。
这是我的信息中心代码:
<template>
<div class="">
<NavDash />
<div class="container pb-5 pt-5">
<div class="row">
<div class="col d-flex align-items-center">
<h3>Dashboard</h3>
<p class="ml-auto">{{ $store.state.user.email }}</p>
</div>
</div>
<hr>
<AddExercise />
<hr>
<table class="table">
<tbody>
<ExerciseItem
v-for="(exercise_item, index) in this.$store.state.exercises"
:exercise="exercise_item"
key="index"
/>
</tbody>
</table>
</div>
</div>
</template>
<script>
import { firebaseApp, exercisesRef, usersRef } from '../firebaseApp'
import AddExercise from './AddExercise.vue'
import ExerciseItem from './ExerciseItem.vue'
import NavDash from './NavDash.vue'
export default {
methods: {
signOut() {
this.$store.dispatch('signOut')
firebaseApp.auth().signOut()
}
},
props: ['exercise'],
components: {
AddExercise,
ExerciseItem,
NavDash
},
mounted() {
exercisesRef.on('value', snap => {
let exercises = []
snap.forEach(exercise => {
exercises.push(exercise.val())
})
console.log('exercises', exercises)
this.$store.dispatch('setExercises', exercises)
})
}
}
</script>
和ExerciseItem.vue:
<template>
<tr>
<td class="text-left">
<h4>{{exercise.title}}</h4>
<p>{{exercise.description}}</p>
</td>
<td>
{{exercise.categories}}
</td>
<td>
<button @click="removeExercise(exercise)">X</button>
</td>
<td>
<router-link to="/exercises/:id">LINK</router-link>
</td>
</tr>
</template>
<script>
export default {
props: ['exercise'],
}
</script>
Exercise.vue:
<template>
<div>
<NavDash />
Exercise {{ id }}
<h4>{{title}}</h4>
<p>{{description}}</p>
</div>
</template>
<script>
import { firebaseApp, exercisesRef, usersRef } from '../firebaseApp'
import NavDash from './NavDash.vue'
export default {
props: ['id'],
components: {
NavDash
}
}
</script>
路由器路径:
{ path: '/exercises/:id',
name: 'Exercise',
component: Exercise,
props: {
default: true
}
}
这是我的Store目录中的Index.js:
import Vue from 'vue'
import Vuex from 'vuex'
import { mutations } from './mutations'
import * as actions from './actions'
import * as getters from './getters'
Vue.use(Vuex)
const state = {
user: {},
exercises: {},
articles: {}
}
export default new Vuex.Store({
state,
mutations,
actions,
getters
})
我尝试按照此处的文档:https://router.vuejs.org/en/essentials/passing-props.html
但我似乎无法使路由器链接正常工作。
非常感谢任何帮助!
谢谢!
答案 0 :(得分:0)
根据您的路线,练习组件会收到id
道具,而不是exercise
道具。我不认为你可以通过路由传递vue-router中的对象,即使你可以,我认为这将是一个不好的做法,因为它必须序列化路由中的对象。
练习组件会收到id
道具,并应使用它来查找练习。通过ajax请求,vuex或其他一些状态源。由于您使用的是vuex,因此可以创建一个getter,它返回一个对象,其中键是exercise id,值是练习。然后,您可以使用id。
Vuex getter
exercisesById(state) {
var obj = {};
state.exercises.forEach(x => {
obj[x.id] = x;
});
return obj;
}
练习组件
<script>
import { firebaseApp, exercisesRef, usersRef } from '../firebaseApp'
import NavDash from './NavDash.vue'
export default {
props: ['id'],
components: {
NavDash
},
computed: {
exercise() {
return this.$store.getters.exercisesById(this.id);
}
},
}
</script>