vue之mixin混入偷懶技術
阿新 • • 發佈:2020-11-13
mixin分發vue元件中的可複用功能
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>mixin的應用</title> </head> <body> <div id='app'> </div> <script src="./vue.js"></script> <script> // 一個是模態框 一個提示框 // 它們看起來不一樣,用法不一樣,但是邏輯一樣(切換boolean) /* // 全域性的mixin 要格外小心 因為每個元件例項建立是,它都會被呼叫 Vue.mixin({ }) */ const toggleShow = { data() { return { isShow: false } }, methods: { toggleShow() { this.isShow = !this.isShow } } } const Modal = { template: ` <div v-if='isShow'><h3>模態框元件</h3></div> `, // 區域性的mixin mixins: [toggleShow] } const ToolTip = { template: ` <div v-if='isShow'> <h2>提示框元件</h2> </div> `, mixins: [toggleShow] } new Vue({ el: "#app", data: { }, components: { Modal, ToolTip }, template: ` <div> <button @click='handleModel'>模態框</button> <button @click='handleToolTip'>提示框</button> <Modal ref='modal'></Modal> <ToolTip ref='toolTip'></ToolTip> </div> `, methods: { handleModel() { this.$refs.modal.toggleShow(); }, handleToolTip() { this.$refs.toolTip.toggleShow(); } }, }) </script> </body> </html>