美文网首页
Vue.js高级功能之自定义指令、插件、单文件组件

Vue.js高级功能之自定义指令、插件、单文件组件

作者: 壹点微尘 | 来源:发表于2017-09-09 16:07 被阅读142次

1.自定义指令 directive

以自定义v-css指令为例:

  • 局部指令
<script>
  export default {
    //自定义v-css指令
    directives: {
      css: {
        inserted (el, bind) {
          let styleObj = bind.value
          let arr = []
          for (let key in styleObj) {
            arr.push(key + ':' + styleObj[key])
          }
          arr = arr.join(';')
          el.style.cssText = arr
        }
      }
    }
</script>
  • 全局指令
    main.js文件中自定义全局的指令
Vue.directive('css', {
  inserted (el, binding) {
    let styleObj = binding.value
    let arr = []
    for (let key in styleObj) {
      arr.push(key + ':' + styleObj[key])
    }
    arr = arr.join(';')
    el.style.cssText = arr
  }
})
使用自定义指令
<p v-css="{color: 'orange', 'font-size': '24px'}">我是p标签</p>
自定义指令v-css修改p标签样式

2.插件

具体请参考官方文档:https://cn.vuejs.org/v2/guide/plugins.html

导入插件(以vue-router为例)
执行命令:npm install vue-router --save

如果某个插件需要全局使用,可以把该插件导入在main.js文件中,在Vue.use(xxx插件)注册下,这样就可以全局调用该插件的方法了!

注意:有些插件需要实例化
设置全局插件

3.单位件组件

scoped:局部的
如果没有用scoped,那么该样式就会泄漏致全局(所有引入该组件的父组件都会引入这样的样式)

可以根据实际情况,具体需求,决定是否使用 scoped 修饰

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
  font-weight: normal;
}
......
</style>

相关文章

网友评论

      本文标题:Vue.js高级功能之自定义指令、插件、单文件组件

      本文链接:https://www.haomeiwen.com/subject/ypoojxtx.html