Vue中的自定义函数和指令

全局自定义组件

Vue.component('component-name',{
	data(){
		return{
			count:0
		}
	},
	template:
	`<button @cick="addCount">{{count}}</button>`,
	methods:{
	addCount(){
		this.count++
	}
}
})
  • vue-cli3.0中可能会报错。在vue.config.js中设置。
module.exports = {
	runtimeCompiler:true
}
  • 为什么data不对象,而选择用一个闭包函数。
  • 因为要保证每个引用data中数值的内容都能给出一份新的拷贝,如果是一个对象,
  • count和count之间会互相影响。

全局注册指令

Vue.directive('watch-color',{
	//第一次绑定的时候调用
	bind(el /*Dom节点*/
	,bind/*bind 详细信息 比如value,有很多属性*/){
	},
	//节点更新的时候调用
	update(el,bind){
		console.log(bind.value)
		//el.focus()
		var backgroundColor  = bind.value.backgroundColor;
		var color = bind.value.color;
		el.style.color = color;
		el.style.backgroundColor = backgroundColor;
	},
	//插入时调用
	inserted(el,bind){
	},
	//解绑时调用
	unbind(el,bind){}
})

	<div v-watch-color="{backgroundColor:red,color:white}"></div>

猜你喜欢

转载自blog.csdn.net/gexiaopipi/article/details/89299130
今日推荐