[轉]vue 中 mixins 的使用
阿新 • • 發佈:2021-07-09
mixins(混入)就是定義了一部分公共的方法、計算屬性或者鉤子函式等 vue 元件中的可複用功能,然後混合進各個元件中使用。下面我們具體來看看怎麼使用。
建立一個 demo.js 檔案,然後 export 給外部使用
export const demoMixins = {
data() {
return {
name: '我是 mixins 中的字串 name',
user: '我是 mixins 中的字串 user'
}
},
created() {
console.log('我是 mixins 中的鉤子函式 created')
this.hello()
this.say()
this.pay()
},
methods: {
hello() {
console.log('我是 mixins 中的函式 hello')
},
say() {
console.log('我是 mixins 中的函式 say')
}
}
}
在元件中引入這個 mixins 物件
<template>
<div></div>
</template>
<script>
import { demoMixins } from '@/mixins/demo'
export default {
mixins: [demoMixins],
data() {
return {
name: '我是元件中的字串 name',
sex: '我是元件中的字串 sex'
}
},
created() {
console.log('我是元件中的鉤子函式 created')
this.hello()
this.say()
this.pay()
},
methods: {
hello() {
console.log('我是元件中的函式 hello')
},
pay() {
console.log('我是元件中的函式 pay')
}
}
}
</script>
我們先來看看執行結果
// => 我是 mixins 中的鉤子函式 created
// => 我是元件中的函式 hello
// => 我是 mixins 中的函式 say
// => 我是元件中的函式 pay
// => 我是元件中的鉤子函式 created
// => 我是元件中的函式 hello
// => 我是 mixins 中的函式 say
// => 我是元件中的函式 pay
總結
- 混入物件的鉤子將在元件自身鉤子之前呼叫。
- 值為物件的選項,例如
data
、methods
、components
和directives
,將被合併為同一個物件。兩個物件鍵名衝突時,取元件物件的鍵值對。 - 混入物件中可以使用和呼叫元件自身變數和函式,且與在元件自身中使用情況一樣。
版權屬於:瞭月
本文連結:https://www.lervor.com/archives/141/
版權宣告:本文為瞭月原創文章,轉載請附上原文出處連結和本宣告。