【发布时间】:2021-01-05 04:57:43
【问题描述】:
我可能缺少 VueJS 的一些概念,所以我需要这方面的帮助。我做了一个example 让我的问题更清楚。假设我有一些多功能组件,例如modal 窗口。我正在从 Vuex 获取数据。
./components/modal.vue
<script>
export default {
methods: {
modalClose() {
this.$store.commit("modalClose");
},
},
computed: {
body() {
return this.$store.state.modal.body;
},
footer() {
return this.$store.state.modal.footer;
},
show() {
return this.$store.state.modal.show;
},
},
};
</script>
<template>
<div class="wrap" @click.self="modalClose" v-if="show">
<div id="modal" class="modal">
<div class="modal-body" v-html="this.body">body</div>
<div class="modal-footer" v-html="this.footer">footer</div>
</div>
</div>
</template>
<style>
/* whatever */
</style>
我有another component,它设置了 Vuex 数据并使用我的模态组件来显示数据。它工作正常 - 它呈现数据。但在某些时候,我需要处理模态窗口中的数据,而这正是我丢失它的地方。
./components/persons.vue
<script>
export default {
data: function () {
return {
persons: [
{ name: "John Johnson", id: 1 },
{ name: "David Lynch", id: 2 },
{ name: "Marshall Attack", id: 3 },
],
};
},
methods: {
showModal: function (person) {
this.$store.commit("modal", {
body: "Name: " + person.name,
footer: `<a href="#" person-id="${person.id}">Add</a>`,
});
},
addPerson: function (id) {
// how to trigger this function with "Add" button?
console.log("Success! Person " + id + " was added!");
},
},
};
</script>
<template>
<div id="page1">
<div v-for="person in persons" :key="person.id">
{{ person.name }}
<a href="#" @click="showModal(person)"> Open modal </a>
</div>
</div>
</template>
在这个例子中你可以看到方法addPerson。它属于persons.vue,它应该通过单击模态窗口内的“添加”按钮来执行(需要参数)。所以,我有两个问题:
- 我该怎么做?
- 我是否在灌输不良做法?
P.S.我读到了$emit,但我没有任何运气。
【问题讨论】:
标签: javascript vue.js