不是为了生成消息,我正在使用这种方法。
这是 HTML 部分:
<template>
<div>
<div class="col-md-12">
<div class="alert alert-success alert-dismissible" v-if="registration.isFinished">
<button type="button" data-dismiss="alert" aria-hidden="true" class="close">×</button>
<h4><i class="icon fa fa-check"></i> {{ success.msg }} user "{{ field.user.name }}" created! </h4>
<h4><i class="icon fa fa-check"></i> {{ success.desc }} user "{{ field.user.name }}" created!
Click <router-link to="/profile">Here</router-link> to view your new profile </div>
</div>
</div>
</template>
您可以看到我正在使用 registration.isFinished
来显示成功消息,然后显示 success.msg
和 success.desc
.
现在这是 JS 版本。
export default {
data () {
return {
registration : {
isFinished: false;
},
success: {
msg: '',
desc: ''
}
}
},
methods: {
registerUser() {
// if user is registered
this.registration.isFinished = true
this.success.msg = 'Congratulations'
this.success.desc = 'Your account has been created'
}
}
}
现在,如果这只是为了在一个组件上显示一条消息,那就没问题了……但我还有其他通知,……例如:错误、信息……以及我所有的页面。因此,我的应用中出现了很多重复的内容。
有什么办法可以减少代码重复?我知道答案在于制作组件,但我不确定这是如何完成的
最佳答案
您确实需要制作一个“警报组件”。
它是这样工作的:
<template>
<div>
<div class="alert alert-dismissible" :class="'alert-' + type">
<h4>{{ title }}</h4>
<slot></slot>
</div>
</div>
</template>
<script>
export default {
props: {
title: {
type: String,
required: false
},
type: {
type: String,
required: false,
default: 'success'
}
}
}
</script>
这就是您在其他组件中使用它的方式:
<template>
<div>
<alert title="The title of my component" type="success">
The content of my alert
</alert>
</div>
</template>
<script>
import Alert from './Alert.vue'
export default {
components: {
Alert
}
}
</script>
如您所见,Alert 组件接受两个属性,title 和 type。由于组件中的 :class="'alert-' + type"
,该类型将定义您的警报颜色。
希望你能成功
关于vue.js - 为vuejs创建消息通知时如何避免代码重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46603005/