《零散知识点 · Vue-admin 模板项目》
    		       		warning:
    		            这篇文章距离上次修改已过418天,其中的内容可能已经有所变动。
    		        
        		                
                在Vue-admin模板项目中,我们可能需要创建一个全局的提示组件,这样在任何页面需要显示信息时,都可以使用这个组件。以下是一个简单的实现:
<template>
  <div class="message-box" v-show="isShow">
    {{ message }}
  </div>
</template>
 
<script>
export default {
  data() {
    return {
      message: '',
      isShow: false
    };
  },
  methods: {
    show(msg) {
      this.message = msg;
      this.isShow = true;
      setTimeout(() => {
        this.isShow = false;
      }, 3000); // 显示3秒后自动消失
    }
  }
};
</script>
 
<style scoped>
.message-box {
  position: fixed;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  padding: 10px;
  background-color: #333;
  color: white;
  border-radius: 5px;
}
</style>在主入口文件或者任何全局性的js文件中,我们可以这样使用这个组件:
import Vue from 'vue'
import MessageBox from './components/MessageBox.vue'
 
// 创建一个全局的MessageBox实例
const MessageBoxInstance = Vue.extend(MessageBox)
const instance = new MessageBoxInstance().$mount()
document.body.appendChild(instance.$el)
 
// 定义全局的showMessage函数
function showMessage(msg) {
  instance.show(msg)
}
 
// 在Vue原型上添加showMessage方法
Vue.prototype.$showMessage = showMessage在任何组件内,你可以通过this.$showMessage('这是一条全局消息')来显示消息。这样,你就创建了一个全局可用的提示组件,并且可以在任何页面上显示信息。
评论已关闭