在Vue.JS中羽毛图标用法

Kyl*_*ent 1 icons custom-data-attribute vue.js vuejs2

我一直在尝试在新的vue项目中使用feather-icons.我首先使用vue-clie工具初始化项目:

vue init webpack
Run Code Online (Sandbox Code Playgroud)

一旦完成,我跑了:

npm install
npm run dev
Run Code Online (Sandbox Code Playgroud)

之后我通过npm安装了feather-icons,如下所示:

npm install --save feather-icons
Run Code Online (Sandbox Code Playgroud)

完成后,我尝试通过导入main.js文件中的模块来使用图标:

main.js:

import 'feather-icons'

import Vue from 'vue'
import App from './App'
import router from './router'

Vue.config.productionTip = false

new Vue({
  el: '#app',
  router,
  template: '<App/>',
  components: {
    App
  }
})
Run Code Online (Sandbox Code Playgroud)

然后我尝试在Hello组件中使用一个图标:

Hello.vue:

<template>
  <div>
    <h1> Hello World!</h1>
    <i data-feather="flag"></i>
  </div>
</template>

<script>
  export default {
    name: 'hello',
    data() {
      return {
        msg: 'Welcome to Your Vue.js App'
      }
    }
  }

</script>
<style>
</style>
Run Code Online (Sandbox Code Playgroud)

执行期间未检测到错误,但图标集拒绝工作.我已经尝试将feather-icons直接包含在index.html文件中,但问题仍然存在.

我猜是什么导致这与调用feather-icons所需的i标签上的data-feather属性有关.

我已经在这里待了将近几个小时,但我尝试的任何东西似乎都没有用.任何帮助,将不胜感激.谢谢.

更新1: 根据@ yuriy636的建议,我在我的App组件中导入了feather-icons,然后在mount中调用了feather.replace():

App.vue:

<template>
  <div id="app">
    <router-view></router-view>
  </div>
</template>

<script>

  import feather from 'feather-icons'

  export default {
    name: 'app',

    mounted() {
      feather.replace();
    }
  }

</script>

<style>
</style>
Run Code Online (Sandbox Code Playgroud)

更新2:

正如@smarx所指出的,有一个名为vue-feather-icons的模块,可以方便地使用带有vue的羽毛图标.只需安装它,导入并使用它.这似乎解决了这个问题.

use*_*559 8

总结评论主题并为后代提出另一种解决方案:

  1. 原始代码的问题是缺少调用feather.replace,它会查找具有data-feather属性的所有元素,并用适当的图标的SVG替换它们.
  2. 调用feather.replacemounted钩是简单的用例不够好,但它不允许图标改变.(一般来说,让非Vue代码修改你正在使用Vue进行渲染的HTML是个坏主意.)例如,<i v-bind:data-feather="iconName"></i>不允许后续更新.
  3. vue-feather-icon 似乎是一个与Vue更好地集成的项目.

以下是使用"vanilla" feather-icons而不会遇到上述问题的更好方法.在这里,我们div使用调用的计算属性动态更新a的HTML内容和相应的图标SVG feather.toSvg:

<template>
  <div id="app">
    <h1>{{ message }}</h1>
    <div v-html="iconSvg"></div>
    <button @click="clicky">Click me</button>
  </div>
</template>

<script>
import feather from 'feather-icons'

export default {
  name: 'app',
  data: function () {
    return {
      message: 'Hello, World!',
      icon: 'flag'
    }
  },
  computed: {
    iconSvg: function () {
      return feather.toSvg(this.icon)
    }
  },
  methods: {
    clicky: function () {
      this.message = 'clicked'
      this.icon = 'circle'
    }
  }
}
</script>
Run Code Online (Sandbox Code Playgroud)

  • 谢谢!我只是想补充一下 `feather.toSvg()` 已被弃用,我们应该使用 `feather.icons[name].toSvg()` 代替 (2认同)