vue 消息组件|子组件|组件相互通信
2018年11月15日1.编辑子组件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
<template> <div v-show="show" :class="`alert alert-${type} alert-dismissible`"> <button @click="close" type="button" class="close"><span>×</span></button> {{ msg }} </div> </template> <script> export default { name: 'Message', props: { //这是子组件间和外界通讯的方式 // 是否显示消息框 show: { type: Boolean, default: false }, // 消息框的类型 type: { type: String, default: 'success' }, // 消息 msg: { type: String, default: '' } }, watch: { show(value) { if (value) { this.$nextTick(() => { this.$el.scrollIntoView(true) }) } } }, methods: { close() { this.$emit('update:show', false) //只能这样更新show 否则报错 } } } </script> <style scoped> </style> |
2.全局注册
src/components/index.js
1 2 3 4 |
import Vue from 'vue' import Message from './Message' Vue.component('Message', Message) |
src\main.js
1 2 3 4 5 6 7 |
. . . import './components' //引入组件 . . . |
3.使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
<template> <div class="row"> <div class="col-md-4 col-md-offset-4 floating-box"> <!--消息提示标签开始--> <Message :show.sync="msgShow" :type="msgType" :msg="msg"/> <!--消息提示标签结束--> <button type="submit" class="btn btn-lg btn-success btn-block" @click="register"> <i class="fa fa-btn fa-sign-in"></i> 提示消息 </button> </div> </div> </template> <script> export default { name: 'Register', data() { return { msg: '', // 消息 msgType: '', // 消息类型 msgShow: false // 是否显示消息,默认不显示 } }, methods: { register(e) { this.showMsg('提示一个消息') }, showMsg(msg, type = 'warning') { this.msg = msg //消息内容 this.msgType = type //消息类型 this.msgShow = false //是否显示 this.$nextTick(() => { this.msgShow = true }) } } } </script> |