Ant Design Vue Mentions提及@功能和# 话题功能

Ant Design Vue提供了Mentions组件来实现类似@和#话题的功能,比如在微博和微信群中我们会用@符号去提醒某个人注意,也会用#符号去创建新的话题,Ant Design Vue在1.5.0+新增了此功能,用起来也特别的简单。

基本用法

<template>
  <a-mentions v-model="value" @change="onChange"
   @select="onSelect" style="width:300px">
    <a-mentions-option value="google.com">
      google
    </a-mentions-option>
    <a-mentions-option value="itxst.com">
      itxst
    </a-mentions-option>
    <a-mentions-option value="baidu.com">
      baidu
    </a-mentions-option>
  </a-mentions>
</template>
<script>
export default {
  data() {
    return {
      value: '@itxst.com', //默认值
    };
  },
  methods: {
    //选择事件
    onSelect(option) {
      alert('你选择了:'+JSON.stringify(option.value));
    },
    onChange(value) {
      console.log('Change:', value);
    },
  },
};
</script

在线试一试

异步加载

实现也比较简单,search事件向服务器请求数据,然后更新option即可,加载数据时建议添加一个loading变量来防止数据还没请求完成,用户由输入其他字符造成重复往请求加载的情况。

<template>
  <a-mentions v-model="value" 
  :loading="loading" @search="onSearch" 
  @select="onSelect" style="width:300px">
    <a-mentions-option :value="item.name" v-for="item in options" :key="item.value">
      {{item.value}}
    </a-mentions-option> 
  </a-mentions>
</template>
<script>
export default {
  data() {
    return {
      value: '@itxst.com',
      loading:false,//是否正在加载数据
      options:[]    //数据集
    };
  },
  methods: {
    //选择事件
    onSelect(option) {
      alert('你选择了:'+JSON.stringify(option.value));
    },
    onSearch(keyword) {
       var that=this;
       if(that.loading==true) return;
       that.loading=true;//设置正在加载数据
       setTimeout(function(){
         that.loadData(keyword);
       },2000)
      
    },
    //模拟向服务器请求数据
    loadData(keyword)
    {
      var that=this;
      that.options=[];
      for(var i=0;i<10;i++)
      {
        that.options.push({name:'n'+i,value:i});
      }
      //数据加载完成
      that.loading=false;
    }
  },
};
</script>

自定义触发字符

<template>
  <a-mentions
    placeholder="输入 @或#或$ 试试看"
    :prefix="['@', '#','$']"
    @search="onSearch"
    style="width:300px"
  >
    <a-mentions-option v-for="value in options[prefix] || []" :key="value" :value="value">
      {{ value }}
    </a-mentions-option>
  </a-mentions>
</template>
<script>
//定义数组
const options = {
  '@': ['Bil Gates', 'Linus Torvalds', 'Windows'],
  '#': ['Linux 1.0', 'Linux 2.0', 'Windows 10'],
  '$': ['人民币', '美元', '英镑'],
};
export default {
  data() {
    return {
      prefix: '@',
      options,
    };
  },
  methods: {
    //根据字符更新数组
    onSearch(_, prefix) {
      console.log(_, prefix);
      this.prefix = prefix;
    },
  },
};
</script>

向上展开

只需要把placement属性设置为"top"即可

<template>
  <a-mentions placement="top">
    <a-mentions-option value="1">
      itxst.com
    </a-mentions-option>
    <a-mentions-option value="2">
      google.com
    </a-mentions-option>
    <a-mentions-option value="3">
      baidu.com
    </a-mentions-option>
  </a-mentions>
</template>