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>