在我的vue.js应用中,我需要在模态中显示自定义数据。我正在使用vue-js-modal
能够在我的应用内的任何位置展示模态:https://www.npmjs.com/package/vue-js-modal
我创建了一个非常简单的自定义模态模板来试用它,称为ItemModal.vue
:
<template>
<modal name="item-modal">
<b>{{item.name}}</b>
</modal>
</template>
<script>
export default {
name: 'item-modal',
props: [ 'item' ]
}
</script>
我能够从ItemList.vue
组件中成功调用它:
<template>
<div id="content">
<item-modal></item-modal>
<li v-for="item in items">
<a v-on:click="showModal( item )">
<span>{{item.name}}</span>
</a>
</li>
</div>
</template>
<script>
import ItemModal from './ItemModal.vue';
import Items from '@/api/items';
export default {
name: 'items',
asyncComputed: {
items: {
async get() {
const items = await Items.getAll();
return items.data;
},
default: []
}
},
methods: {
showModal( item ) {
this.$modal.show('item-modal', { item: item } );
}
},
components: {
ItemModal
}
}
</script>
然而,模态出现了空白。
我在ItemModal.vue
中遗漏了哪些内容,以便能够使用我在showModal
函数中传递给它的数据?
答案 0 :(得分:2)
您应该以这种方式在项目的main.js文件中注册插件:
import VModal from 'vue-js-modal'
Vue.use(VModal)
然后您就可以在项目的任何地方调用show函数:
this.$modal.show('the-name-you-asigned-in-your-modal');
如果你需要将params传递给模态,你可以在beforeOpen事件处理程序中轻松接收它们:
//In the template
<modal name="hello-world" @before-open="beforeOpen"/>
methods: {
beforeOpen (event) {
console.log(event.params.foo);
}
}
我知道你非常接近让它发挥作用,所以我为你提供了一个有效的例子,你可以把它作为参考:
1-在main.js文件中包含插件。
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import VModal from 'vue-js-modal'
Vue.config.productionTip = false
Vue.use(VModal)
/* eslint-disable no-new */
new Vue({
el: '#app',
template: '<App/>',
components: { App }
})
2-创建一个包含模态的组件(我们称之为 Modal.vue )
<template>
<modal name="hello-world" @before-open="beforeOpen">
<div class="wrapper">
<p>{{ itemToShow }}</p>
</div>
</modal>
</template>
<script>
export default {
name: 'HelloWorld',
data: function () {
return {
item: ''
}
},
computed: {
itemToShow: function () {
return this.item
}
},
methods: {
beforeOpen (event) {
this.item = event.params.item;
}
}
}
</script>
<style scoped>
.wrapper {
height: 100%;
width: 100%;
background-color: black;
}
</style>
3-显示模态组件
<template>
<div id="app">
<img src="./assets/logo.png">
<Modal />
<button @click="onClick">
CLICK HERE!
</button>
</div>
</template>
<script>
import Modal from './components/Modal'
export default {
name: 'app',
components: {
Modal: Modal
},
methods: {
onClick() {
this.$modal.show('hello-world', {item: 'Hello world'});
}
}
}
</script>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>