zoukankan      html  css  js  c++  java
  • 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>
  • 相关阅读:
    MySQL字符串中数字排序的问题
    Jquery 实现跨域处理
    mysql中insert into select from的使用
    Mysql索引会失效的几种情况分析(转)
    ASP.Net Web API 输出缓存(转)
    8 种提升 ASP.NET Web API 性能的方法 (转)
    C#进阶系列——WebApi 异常处理解决方案(转)
    C#使用Log4Net记录日志(转)
    前端传递对象列表到WebApi
    忏悔录
  • 原文地址:https://www.cnblogs.com/steamed-twisted-roll/p/10906091.html
Copyright © 2011-2022 走看看