Vue的命令式组件是一种封装方法,它将功能逻辑封装在组件内部,并通过命令式的方式进行调用和控制。
以下是一个简单的示例代码,演示如何使用命令式调用组件:1. 编写message.vue文件:
<template> <div class="message" v-if="show"> {{label}} </div> </template> <script> export default { data() { return { label: '空消息', show: true } } } </script> <style lang="scss"> .message { position: fixed; top: 20px; right: 10px; color: #fff; background-color: #222; padding: 15px 20px; width: 180px; } </style>2. 实现调用逻辑,messagefun.js文件:
import Vue from 'vue' import Message from './message.vue' const Msg = Vue.extend(Message); export default (options = {}) => { const instance = new Msg({ el: document.createElement('div'), data() { return { label: options.label } } }) document.body.appendChild(instance.$el); window.setTimeout(() => { instance.$data.show = false }, options.time ? options.time : 3000) }3. 挂载到原型,index.js里:
import Vue from 'vue' import P3 from 'pages/index3.vue' import Coms from 'pages/page3com/com.js' import msg from 'pages/page3com/messagefun.js' Vue.use(Coms) Vue.prototype.$msg = msg; new Vue({ el: '#p3', render: h => h(P3) })4. 调用:
this.$msg({ label: '我是一个消息', time: 4000 });
网友回复