1 注册
在 src/components
下新建 index.js
文件,复制贴入以下代码:
注册全局组件需要使用 Vue.component
,第一个参数 ‘Message‘
是组件名称,第二个参数 Message
是一个对象或者函数,我们这里是一个对象。(vue-cli模板下)
import Message from ‘./Message‘Vue.component(‘Message‘, Message)
2 引用
打开 src/main.js
文件,引入 ./components
:
import Vue from ‘vue‘import App from ‘./App‘import router from ‘./router‘import ‘./directives‘import ‘./components‘
我们通过引入 ./components/index.js
,执行其中代码,就可以使用其内部注册的所有组件了。
3 使用
在目标组件的 data
中添加了 3 个消息组件相关的属性 msg
、msgType
和 msgShow
<script>import createCaptcha from ‘@/utils/createCaptcha‘import ls from ‘@/utils/localStorage‘export default { ?name: ‘Register‘, ?data() { ???return { ?????captchaTpl: ‘‘, // 验证码模板 ?????username: ‘‘, // 用户名 ?????password: ‘‘, // 密码 ?????cpassword: ‘‘, // 确认密码 ?????captcha: ‘‘, // 验证码 ?????msg: ‘‘, // 消息 ?????msgType: ‘‘, // 消息类型 ?????msgShow: false // 是否显示消息,默认不显示 ???} ?},
然后在 methods
中添加了一个 showMsg
的方法用来改变当前的消息;
?methods: { ???login(user) { ?????????ls.setItem(‘user‘, user) ?????????this.showMsg(‘注册成功‘, ‘success‘) ???}, ???showMsg(msg, type = ‘warning‘) { ???????this.msg = msg ???????this.msgType = type ???????this.msgShow = false ???????this.$nextTick(() => { ???????????this.msgShow = true ???????}) ???} ?}}</script>
vue.js注册引用全局消息组件
原文地址:https://www.cnblogs.com/KulaAi/p/10280168.html