• vue + mixin混入对象使用


    vue提供的混入对象mixin,类似于一个公共的组件,其他任何组件都可以使用它.我更经常的是把它当成一个公共方法来使用
    在项目中有些多次使用的data数据,method方法,或者自定义的vue指令都可以放到mixin中,引入到各自的组件就可以使用,非常方便.这里写一下局部的混入组件使用,不建议在项目中使用全局混入..
     
    首先写一个mixin.js文件,可以放在common公共组件中

    src/components/common/mixin.js
    // 你可以定义多个mixin对象,在里面就和普通的组件一样,定义data,method
    export const mymixin = {
      data() {
        return {
          msg: 'hello word, from mymixin'
        }
      },
    
      // 自定义指令
      directives: {
        focus: {
          inserted: function (el) {
            el.focus()
          }
        }
      },
    
      methods: {
        // 处理图片方法
        handleImg (url) {
          if (url && url.indexOf('.jpg') > -1) {
            return url
          } else return 'https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=1840587501,62677872&fm=27&gp=0.jpg'
        }
      }
    }
    在组件中引入使用,在混入对象中定义的data,method会被合并到当前组件中,可以直接使用混入对象里的data
    <template>
      <div>
        mixintest
        <h2>{{msg}}</h2>
        调用mixin方法:<img :src="handleImg('http://pic.58pic.com/58pic/15/17/01/47U58PICVQJ_1024.png')" alt="">
        <h4>自动获取焦点</h4>
        <input type="text" v-focus>
      </div>
    </template>
    <script>
      import {mymixin} from './common/mixin'
    
      export default {
        name: 'mymixin',
        mixins: [mymixin],
        components: {
    
        },
        data() {
          return {
    
          }
        },
        methods: {
          
        }
    
      }
    </script>
    <style scoped>
    
    </style>

    使用效果:

    如果引入组件定义的数据和混入对象的名称重复,组件的数据会覆盖混入对象的属性
     
    <template>
      <div>
        mixintest
        <h2>{{msg}}</h2>
        调用mixin方法:<img :src="handleImg('http://pic.58pic.com/58pic/15/17/01/47U58PICVQJ_1024.jpeg')" alt="">
        <h4>自动获取焦点</h4>
        <input type="text" v-focus>
      </div>
    </template>
    <script>
      import {mymixin} from './common/mixin'
    
      export default {
        name: 'mymixin',
        mixins: [mymixin],
        components: {
    
        },
        data() {
          return {
            msg: '自己组件的数据'
          }
        },
        methods: {
          
        }
    
      }
    </script>
    <style scoped>
    
    </style>
  • 相关阅读:
    Matlab下imwrite,Uint16的深度图像
    ROS indigo下Kinect v1的驱动安装与调试
    ROS indigo下Kinect v2的驱动安装与调试
    Ubuntu14.04(indigo)实现RGBDSLAMv2(数据集和实时Kinect)
    Ubuntu验证查看库的安装情况-copied
    Ubuntu常用命令及git常用命令-copied
    针孔相机模型和相机镜头畸变模型
    Ubuntu14.04-OpenCV2和3共存相关设置
    Kinect v1 (Microsoft Kinect for Windows v1 )彩色和深度图像对的采集步骤
    window和Linux下Redis的安装及运行
  • 原文地址:https://www.cnblogs.com/steamed-twisted-roll/p/10906091.html
Copyright © 2020-2023  润新知