作用:代码复用

    1. <!DOCTYPE html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    6. <meta http-equiv="X-UA-Compatible" content="ie=edge">
    7. <title>Document</title>
    8. </head>
    9. <body>
    10. <div id='app'>
    11. {{msg}}
    12. </div>
    13. <script src="./vue.js"></script>
    14. <script>
    15. const myMixin = {
    16. data(){
    17. return {
    18. msg:"123"
    19. }
    20. },
    21. created(){
    22. this.sayHello();
    23. },
    24. methods: {
    25. sayHello() {
    26. console.log('hello mixin');
    27. }
    28. },
    29. }
    30. // mixin来分发Vue组件中的可复用功能
    31. new Vue({
    32. el:"#app",
    33. data:{
    34. msg:"mufeng"
    35. },
    36. created(){
    37. console.log(1111);
    38. },
    39. mixins:[myMixin]
    40. })
    41. </script>
    42. </body>
    43. </html>

    应用

    1. <!DOCTYPE html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    6. <meta http-equiv="X-UA-Compatible" content="ie=edge">
    7. <title>mixin的应用</title>
    8. </head>
    9. <body>
    10. <div id='app'>
    11. </div>
    12. <script src="./vue.js"></script>
    13. <script>
    14. // 一个是模态框 一个提示框
    15. // 它们看起来不一样,用法不一样,但是逻辑一样(切换boolean)
    16. /*
    17. // 全局的mixin 要格外小心 因为每个组件实例创建是,它都会被调用
    18. Vue.mixin({
    19. })
    20. */
    21. const toggleShow = {
    22. data() {
    23. return {
    24. isShow: false
    25. }
    26. },
    27. methods: {
    28. toggleShow() {
    29. this.isShow = !this.isShow
    30. }
    31. }
    32. }
    33. const Modal = {
    34. template: `
    35. <div v-if='isShow'><h3>模态框组件</h3></div>
    36. `,
    37. // 局部的mixin
    38. mixins: [toggleShow]
    39. }
    40. const ToolTip = {
    41. template: `
    42. <div v-if='isShow'>
    43. <h2>提示框组件</h2>
    44. </div>
    45. `,
    46. mixins: [toggleShow]
    47. }
    48. new Vue({
    49. el: "#app",
    50. data: {
    51. },
    52. components: {
    53. Modal,
    54. ToolTip
    55. },
    56. template: `
    57. <div>
    58. <button @click='handleModel'>模态框</button>
    59. <button @click='handleToolTip'>提示框</button>
    60. <Modal ref='modal'></Modal>
    61. <ToolTip ref='toolTip'></ToolTip>
    62. </div>
    63. `,
    64. methods: {
    65. handleModel() {
    66. this.$refs.modal.toggleShow();
    67. },
    68. handleToolTip() {
    69. this.$refs.toolTip.toggleShow();
    70. }
    71. },
    72. })
    73. </script>
    74. </body>
    75. </html>