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>
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>