Giter Site home page Giter Site logo

vue-avatar's Introduction

vue-avatar

Build Status

An avatar component for vue.js.

This component display an avatar image and if none is provided fallback to the user initials. This component is highly inspired from react-user-avatar.

Rules used to compute user initials:

  • divide the username on space and hyphen
  • use the first letter of each parts
  • never use more than three letters as initials
  • if the username is divided in more than three parts and has part starting with an uppercase, skip parts starting with a lowercase.

You can find a few examples and the documentation here

Installation

npm install vue-avatar

Version

Vuejs version vue-avatar version
^1.0.18 ^1.3.0
^2.0.0 ^2.0.0

Usage

vue-avatar is a UMD module, which can be used as a module in both CommonJS and AMD modular environments. When in non-modular environment, Avatar will be registered as a global variable.

ES6

import Avatar from 'vue-avatar'

export default {
  ...
  components: {
    Avatar
  },
  ...
}

After that, you can use it in your templates:

<avatar username="Jane Doe"></avatar>

CommonJS

var Vue = require('vue')
var Avatar = require('vue-avatar')

var YourComponent = Vue.extend({
  ...
  components: {
    'avatar': Avatar.Avatar
  },
  ...
})

Browser

<script src="path/to/vue/vue.min.js"></script>
<script src="path/to/vue-avatar/dist/vue-avatar.min.js"></script>

new Vue({
  ...
  components: {
    'avatar': VueAvatar.Avatar
  },
  ...
})

Props

NameRequiredDefaultTypeDescription
username N - String The user name that will be used to compute user initial.
initials N - String Force the displayed initials by overriding the computed ones.
inline N false Boolean Uses inline-flex instead of flex
src N - String Path to the avatar image to display.
:customStyle N - Object A custom style object to override the base styles.
backgroundColor N - String The avatar background color to use if no image is provided. If none is specified, a background color will be picked depending on the user name length.
color N - String The font color used to render the user initials. If none is provided, the background color is used to compute the font color.
:lighten N 80 Number A factor by which the background color must be lightened to produce the font color. Number between [-100,100].
:size N 50 Number The avatar size in pixel.
:rounded N true Boolean True if the avatar must be rounded.
:parser N [getInitials()](https://github.com/eliep/vue-avatar/blob/master/src/Avatar.vue#L8-L27) Function Custom parser to manipulate the string (the parser takes 2 params: a String and the default parser). It must return a String.

Event

NameArgumentsDescription
@avatar-initials username (the value of the username props), initials (the value of the computed initials or the initials props if any) This event is trigger when the component is ready with component username and initial.

Build Setup

# install dependencies
npm install

# serve gh pages with hot reload at localhost:8080/gh-pages/index.html
npm run dev

# build
npm run bundle

Test

npm test

License

Released under the MIT License.

vue-avatar's People

Contributors

andreasvirkus avatar danielbprice avatar dimitri-koenig avatar e200 avatar eliep avatar hailwood avatar haroenv avatar loghorn avatar maximechareyron avatar negezor avatar pascalwengerter avatar viqtor avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

vue-avatar's Issues

Webpack resolve image

I am trying to add image to the src attribute, but it's not working... How does avatar resolve images? I am working with Nuxt.js which uses Webpack to resolve images.

Does not work <avatar src="@/assets/img/profiles/test.png">

works <avatar src="https://eliep.github.io/vue-avatar/static/darth-vader.png">.

If I do this <img src="@/assets/img/profiles/test.png">, the image is displayed.

Thanks

Fall back to initials when image load fails

When the provided image fails to load (URL doesn't exist or is inaccessible), the avatar could display the default content (initials).

Vue exposes a convenient @error event on this, so we could do <img :src="source" @error="displayInitials" />

Would you accept a PR on this?

这种数组怎么渲染?

<avt @avatar-initials="item.clientContacts" username="item.clientContacts" initials="item.clientContacts" :size="25" :lighten="88">

说明:clientContacts 是个数组,比如['张三','李四] ,我的写法应该是有问题的,因为效果不对,请问官方文档也没例子,可否写一个例子哈,谢了

Dynamique username

Hello,
How can I use this plugin with dynamique data ( username )..

Merci

i can't bind username.

I use this code:

 <avatar
     class="avatar"
     :username="item.username"
     :size="130"
>

In console, i have some error:

  1. Error in render: "TypeError: Cannot read property 'length' of undefined"
  1. Cannot read property 'length' of undefined
  1. Cannot read property 'split' of undefined

but that is not undefined

bind a variable to username

I tried

<avatar :rounded="false" :size="100" class="picture card border-white rounded shadow" :username="data.name"></avatar>

but it does not work.
how to solve this?

@avatar-initials event

Hi, I'm dynamically building initials based on user input's name and would like to use @avatar-initials event to synchronize it with vuex state. Unfortunately as I can see in the source this event is emitted only on mounted () lifecycle phase. Would you mind if I create PR for firing this event every time initials are updated ? (#13)

how to invoke the .vue files

Hi,
I am working angular 2 application.
I used this module as per the document:

1.npm install vue-avatar

  1. In the .ts file I have called this statement:

import Avatar from 'vue-avatar/dist/Avatar'

export default {

components: {
Avatar
},
}

when i try to run the application i got the error as : http://localhost:3001/node_modules/vue-avatar/dist/Avatar.js 404 (Not Found)

Please let me know how to call the .vue file or what is wrong here?

TypeError: Cannot read properties of undefined (reading '_c')

Hello Everyone! I need your help.

I am using this package in Vue3 (using Vite also). But everytime I try to use it, it shows me a Type error: vue-avatar.min.js:1 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading '_c')

Here is my component:

<template>
  <avatar
    :username="name"
    :src="src"
    color="#2B43D8"
    background-color="#D8E0FE"
    :rounded="true"
    :size="size"
  />
</template>

<script>
import Avatar from "vue-avatar";
import md5 from "md5";
export default {
  name: "MyAvatar",
  components: {
    Avatar,
  },

 props: {
    name: {
      type: String,
      required: true,
    },
    src: {
      type: String,
      default: "",
    },
    size: {
      type: Number,
      default: 24,
    },
    email: {
      type: String,
      default: "",
    }
  }
}
</script>

And this is how I use it:
<MyAvatar name='Jane doe' email='[email protected]' src='https://images.unsplash.com/photo-1494790108377-be9c29b29330?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=facearea&facepad=4&w=256&h=256&q=60' />

How can i fix this folks? Please help!!

more shapes

Hi,

Can you also add more shape like:

  • square rounded
  • hexagon
  • pentagon
  • rhombus

Using vue-avatar in vue 3

Hi, I'm trying to use the vue-avatar in vue 3. Everything seems to check out except that the avatar doesn't display but I can see the name bound to the div element in the console. If it should work in vue 3, could the problem be my usage? Thanks

Local path src can't work?

<img src="../../icons/png/1.png"> this code can show local picture
<avatar src="../../icons/png/1.png"></avatar> It has no effect

Add the possibiliy to use username if src is false or null

It could be nice if you can add the feature like if src is null or false, show the username by default. Typical case when someone didn't upload an avatar yet, the src still null so we should use his username (today, we have "width: 64px; height: 64px; background: url("null") no-repeat;" and I don't want to use double "v-if" with double "<avatar>"

grab image data

Hello there,

is it possible to grab the image data once the avatar has been created?

Thank you.

How to use the customStyle property

For now the size accepts only numbers. I want to be able to use 7vw instead of 70px. My idea was to use this:

:customStyle="{ height: '7vw !important;', width: '7vw !important;' }"

But it doesn't work :(

Difference in parsing of props with or without src attribute

With the following code:

<Avatar
    username="Corstian Boerman"
    inline size="30"
    class="mr-3"
    src="https://pbs.twimg.com/profile_images/940157009151721472/nVMbmnJf_400x400.jpg" />
Corstian Boerman
<br />
<br />
<Avatar
    username="Corstian Boerman"
    inline
    size="30"
    class="mr-3" />
Corstian Boerman

The result is quite different:

image

The layout of the last one is how I actually expect the avatar to render.

Looking at the styles applied to the element it seems that after the background image is set no other styles are being applied:

1st element:

<div
    class="vue-avatar--wrapper mr-3"
    style="
        width: 30px;
        height: 30px;
        border-radius: 50%;
        background: transparent url(&quot;https://pbs.twimg.com/profile_images/940157009151721472/nVMbmnJf_400x400.jpg&quot;) no-repeat scroll 0% 0% / 30px 30px content-box border-box;
    ">
    <!---->
</div>

2nd element:

<div
    class="vue-avatar--wrapper mr-3"
    style="
        width: 30px;
        height: 30px;
        border-radius: 50%;
        background-color: rgb(158, 158, 158);
        font: 12px/301px Helvetica, Arial, sans-serif;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        color: rgb(238, 238, 238);
    ">
    <span>CB</span>
</div>

Avatar show with 0x0 pixel size

Hi, i'm using vue-avatar on nuxtjs project, I have install avatar to my project and put in on the page/index.vue

<avatar username="Jane Doe" :size="100"></avatar>

When I try to run the project I got 0x0 pixel avatar and if I inspect the html, I saw jut

<avatar username="Jane Doe" size="100" data-v-2a183b29=""></avatar>

any idea how to fix?

Maximum Letters

Could we get an option to set maximum number of letters to appear in the avatar, to handle people with suffixes and other similar situations?

Thanks!

Allow font family to flow naturally from surroundings

This component imposes a font selection as follows:

const initialBackgroundAndFontStyle = {
  backgroundColor: this.background,
  font: `${Math.floor(this.size / 2.5)}px/${this.size}px Helvetica, Arial, sans-serif`,
  color: this.fontColor
}

It's certainly possibly to use styles to override that, but it seems inconvenient; usually a component with text in it would naturally match the fonts of the things around it.

It seems like simply changing this to not select a font would be a more hands-off and natural approach.

Inline block for avatar

Most of the time, avatar will be followed by full name. Since the avatar has div element, it pushes the name text to the next line. Can you make avatar as inline-block by default? Otherwise can you provide a props to do it?

Custom parser

Hi there!

First off, thanks for a great component : ) It's a go-to default for most of my projects 💯

Currently, when a passed in name contains parenthesis (e.g. James (Team lead)), the displayed avatar is J(L. Would you be willing to exclude/filter out parenthesis before performing the lookup for the initials? Or a prop which would allow the user to completely ignore the contents of the parenthesis (so either JTL or J would get displayed).

Here's a short repro: https://codesandbox.io/s/1qx82p6k7q

Would be willing to look into it as well, if you're open to contributions

Best,
andreas

Runtime-only build of Vue/Precompiled Templates

Hello, I'm using vue-avatar within my Nuxt project (@nuxt) and get this error on render:

[Vue warn]: You are using the runtime-only build of Vue where the template compiler is not available. Either pre-compile the templates into render functions, or use the compiler-included build.

It works if I reference the compiler-included build in the web pack configuration of Nuxt like this:

build: { extend(config) { config.resolve.alias['vue'] = 'vue/dist/vue.common' } }

Is there another work-around? Like pre-compiling templates on build? I'd be happy to work on a PR.

import don't work (I base on Meteor)

I base on Meteor

<avatar :username="fullName"></avatar>
-----
import Avatar from 'vue-avatar';

components: {
            avatar: Avatar.Avatar,

Get error

You are using the runtime-only build of Vue where the template compiler is not available. Either pre-compile the templates into render functions, or use the compiler-included build.

Doesn't work with vue-cli pwa template

The template uses babel-env but when importing 'vue-avatar/dist/Avatar' I get "Module build failed: Error: Couldn't find preset "es2015" relative to directory". Solved it by installing the babel-preset-es2015 but it would be nice if it wasn't dependent on that.

Interpolation inside attributes has been removed in Vue.js v2.2.4

<avatar username="{{profile.firstName}}" :size="128">

get the following error:

username="{{profile.firstName}}": Interpolation inside attributes has been removed. Use v-bind or the colon shorthand instead. For example, instead of <div id="{{ val }}">, use <div :id="val">.

Change to <avatar :username="profile.firstName" :size="128">

[Vue warn]: Invalid prop: type check failed for prop "username". Expected String, got Undefined. 
(found in <Avatar>)

Improve accessibility of avatar component

I've come across two problems with the vue-avatar component when trying to make my employer's web application meet accessibility (A11Y) requirements:

  1. The wrapping tag is a <div>, which is somewhat limited in its usage. We're wrapping the avatar and username in a <button> to open a user menu dropdown (common behaviour on other websites), but a <div> inside a <button> is not valid HTML5 (discussion with more resources can be found in this thread). I've tried replacing the <div> with a <span> which is allowed inside a <button> and the results looked somewhat the same, so the fix for this should be quick & easy
  2. The contrast between background-color and text-color aren't high enough - their contrast ratio is between 1.53 and 3.8 (from what I've seen), whilst accessibility criteria for colorblind/visually impaired people ask for a contrast ratio of >4.5. This can be fixed quite easily by updating the available color/background-color combinations by ones that pass a color contrast checker

Towards the maintainers of this component: Happy to hear your thoughts and please let me know if opening a PR to resolve the two points from my side is worth the effort 🤓

Font

Hi,

perhaps I overlooked something, but is there no possibility to change the font-family without hacking the component?

Best regards.
Danny

[Bug] Missing background styling after dynamically updating the 'src' property

On initial rendering, the avatar property adds the following CSS when the 'src' property is set:

background: url("src_path") 0% 0% / 100px 100px no-repeat content-box;

However, if the 'src' property is bound to a computed element, which then gets updated after the initial rendering of the avatar element, the CSS background property gets updated to:

background: url("src_path");

Missing 0% 0% / 100px 100px no-repeat content-box; and causing the image to be displayed incorrectly.

Inline avatars display inconsistently

I noticed that <avatar inline>'s with src set versus those with username set have inconsistent alignment with surrounding inline text. The following fiddle hopefully illustrates the problem: https://jsfiddle.net/hnyao14r/2/

Screen Shot 2019-10-24 at 9 09 03 PM

I also show a minor tweak-- adding a zero width space to the wrapper <div>-- which seems to help the situation. I'm not sure I understand enough about CSS and alignment and baselines to know why. Thanks for this nice component!

Better Responsive Support

First of all I don't have any issues, I just wanna explain my situation and how I solved it and maybe you have better idea and might merge this.

Right now I've applied some patches in order to use vue-avatar in card designs as width: 100% property. If I just set width: 100%, then height will be equal to default size. What I need was a fixed 1:1 ratio so I found out https://www.w3schools.com/howto/howto_css_aspect_ratio.asp

image

    <avatar :username="group.name"
            class="card-img-top"
            :customStyle="{width: '100%', height:null, 'padding-top': '100%', 'position' : 'relative'}"
            :src="group.photo_url"
            :rounded="false"
    />

image

I applied and it is working. Now there is another problem. Span is not centered. This is what I did to make it centered.

.vue-avatar--wrapper span{
    display: flex;
    align-items: center;
    justify-content: center;
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
}

I am not a CSS expert. I am just a beginner and all I want is to use this library anywhere I want easily without problem. So this is my solution.

Final Result is

image

image

What do you think?

Using Gravatar for src doesn't work

I'm trying to use a gravatar image for the src prop but the avatar component fails to render. The initials prop of the avatar component are undefined according to Vue.

<avatar :username="jon boc" src="https://www.gravatar.com/avatar/aa6100ff19ebeef51b5617d767f5acd9">

Any thoughts?
Regards

Avatar read by screenreaders

The avatar is a nice visual indicator, however, for screen reader users, it is useless. Please make the screenreader ignore the avatar (add attribute aria-hidden="true" to the inner span) and/or provide an alternative text.

Vue-avatar requires old presets

Webpack stack

ERROR in ./node_modules/babel-loader/lib!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./node_modules/vue-avatar/dist/Avatar.vue

Module build failed: Error: Couldn't find preset "es2015" relative to directory "C:\\Users\\negezor\\node\\shiza\\node_modules\\vue-avatar"
	at C:\Users\negezor\node\shiza\node_modules\babel-core\lib\transformation\file\options\option-manager.js:293:19
	at Array.map (native)
	at OptionManager.resolvePresets (C:\Users\negezor\node\shiza\node_modules\babel-core\lib\transformation\file\options\option-manager.js:275:20)
	at OptionManager.mergePresets (C:\Users\negezor\node\shiza\node_modules\babel-core\lib\transformation\file\options\option-manager.js:264:10)
	at OptionManager.mergeOptions (C:\Users\negezor\node\shiza\node_modules\babel-core\lib\transformation\file\options\option-manager.js:249:14)
	at OptionManager.init (C:\Users\negezor\node\shiza\node_modules\babel-core\lib\transformation\file\options\option-manager.js:368:12)
	at File.initOptions (C:\Users\negezor\node\shiza\node_modules\babel-core\lib\transformation\file\index.js:212:65)
	at new File (C:\Users\negezor\node\shiza\node_modules\babel-core\lib\transformation\file\index.js:135:24)
	at Pipeline.transform (C:\Users\negezor\node\shiza\node_modules\babel-core\lib\transformation\pipeline.js:46:16)
	at transpile (C:\Users\negezor\node\shiza\node_modules\babel-loader\lib\index.js:49:20)
	at Object.module.exports (C:\Users\negezor\node\shiza\node_modules\babel-loader\lib\index.js:174:20)
@ ./node_modules/vue-avatar/dist/Avatar.vue 4:2-90
@ ./node_modules/babel-loader/lib!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./app/views/dashboard/components/layouts/Sidebar.vue
@ ./app/views/dashboard/components/layouts/Sidebar.vue
@ ./node_modules/babel-loader/lib!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./app/views/dashboard/components/App.vue
@ ./app/views/dashboard/components/App.vue
@ ./app/views/dashboard/bundle.js
@ multi ./app/views/dashboard/bundle

Current new babel-preset-env

Vue 3

Hi,

is it possible to add support for Vue3 ?

Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.