vueカスタムtoastコンポーネント
2634 ワード
携帯電話端末のプロジェクト開発では、いくつかのフレームワークのtoast互換性があまりよくなく、単独で修正する必要があり、カスタマイズ性が強くなく、特定のtoastスタイルが必要なのか、スタイルを再構築する必要があるのか、toastコンポーネントがvueのrender関数構築1を使用し、componentsプロジェクトフォルダの下に新しいvueのファイル、コンポーネント(サブコンポーネント)(1.1)としてdataに3つの変数を定義する
(1.2)propsで親コンポーネントから渡されたtopを定義し、toastの上部からの位置をカスタマイズします.後の単位はパーセントです.
(1.3)methodsで関数toastShowを定義する
(1.4)次にrender関数を作成し、toastスタイルを構築する
(1.5)最後にtoastのスタイルを定義し、自分のニーズに合わせてカスタマイズできる
2、親コンポーネントへの導入(2.1)コンポーネントtoastへの導入
(2.2)登録コンポーネントtoast
(2.3)ページにtoastコンポーネントを導入する
(2.4.1)最後に必要な場所でtoastを呼び出す
(2.4.2)最後に必要な場所でtoastを呼び出す(サブコンポーネントtoastコンテンツはHTMLタグを解析できる)
data() {
return {
showToast: false, // toast
toastContent: '', // toast
num: 0 // , setTimeout
}
}
(1.2)propsで親コンポーネントから渡されたtopを定義し、toastの上部からの位置をカスタマイズします.後の単位はパーセントです.
props: {
top: {
type: [String, Number],
required: true,
default: 50
},
},
(1.3)methodsで関数toastShowを定義する
// ,value ,time
toastShow(value, time) {
this.num = this.num + 1 // num+1
if(this.num < 2) {
this.showToast = true // toast
this.toastContent = value // toast
setTimeout(() => {
this.showToast = false
this.num = 0
}, time)
}
}
(1.4)次にrender関数を作成し、toastスタイルを構築する
render: function(createElement) {
return createElement(
'div', {
'class': {
'my-toast': this.showToast
},
'attrs': {
style: `top: ${this.top}%` // top 50 ,
},
domProps: {
innerHTML: this.toastContent // toast HTML
},
},
)
}
(1.5)最後にtoastのスタイルを定義し、自分のニーズに合わせてカスタマイズできる
.my-toast {
white-space: nowrap;
position: fixed;
top: 50%;
left: 50%;
display: flex;
color: #fff;
font-size: 14px;
line-height: 20px;
border-radius: 4px;
align-items: center;
flex-direction: column;
box-sizing: border-box;
-webkit-transform: translate3d(-50%, -50%, 0);
background-color: rgba(0, 0, 0, .7);
padding: 0.1rem 0.2rem;
z-index: 999;
text-align: center;
}
2、親コンポーネントへの導入(2.1)コンポーネントtoastへの導入
import toast from '**************************'
(2.2)登録コンポーネントtoast
components: {
toast,
},
(2.3)ページにtoastコンポーネントを導入する
(2.4.1)最後に必要な場所でtoastを呼び出す
this.$refs.childToast.toastShow(`************`, 2000)
// toast , toast
(2.4.2)最後に必要な場所でtoastを呼び出す(サブコンポーネントtoastコンテンツはHTMLタグを解析できる)
this.$refs.childToast.toastShow(`******
******`, 2000)
//