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,将被合并为同一个对象。两个对象键名冲突时,取组件对象的键值对。
    • 混入对象中可以使用和调用组件自身变量和函数,且与在组件自身中使用情况一样。
    路是自己走出来的,而不是选出来的。
  • 相关阅读:
    tensorflow 2.0 学习 (十) 拟合与过拟合问题
    tensorflow 2.0 学习 (九) tensorboard可视化功能认识
    tensorflow 2.0 学习 (八) keras模块的认识
    tensorflow 2.0 学习 (七) 反向传播代码逐步实现
    tensorflow 2.0 学习 (六) Himmelblua函数求极值
    tensorflow 2.0 学习 (五)MPG全连接网络训练与测试
    arp协议简单介绍
    Pthread spinlock自旋锁
    线程和进程状态
    内核态(内核空间)和用户态(用户空间)的区别和联系·
  • 原文地址:https://www.cnblogs.com/mo3408/p/14414664.html
Copyright © 2011-2022 走看看