zoukankan      html  css  js  c++  java
  • vue 中 mixins 的详细介绍

    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
    

      

    总结

    • 混入对象的钩子将在组件自身钩子之前调用。
    • 值为对象的选项,例如 datamethodscomponents 和 directives,将被合并为同一个对象。两个对象键名冲突时,取组件对象的键值对。
    • 混入对象中可以使用和调用组件自身变量和函数,且与在组件自身中使用情况一样。
    路是自己走出来的,而不是选出来的。
  • 相关阅读:
    【DOS命令】type
    【shell】$符号操作
    【C++百科】STL(Standard Template Library) 标准模板库简介
    【配置与安装】SSH 密钥类型的的选择(RSA, DSA or Other)
    【百科通识】CPU x86/x86-64/x64/i386
    【配置与安装】SSH远程开发
    【百科通识】.bat文件
    【vi】模式切换
    【vim】撤销与回退
    【C++】智能指针
  • 原文地址:https://www.cnblogs.com/mo3408/p/14414664.html
Copyright © 2011-2022 走看看