学习内容
本节课继续学习了 Vue.js 相关知识
1.Vue.js 组件 - 自定义事件
知识点:
父组件是使用 props 传递数据给子组件,但如果子组件要把数据传递回去,就需要使用自定义事件。
我们可以使用 v-on 绑定自定义事件,每个 Vue 实例都实现了事件接口(Events interface),即:
使用 $on(eventName) 监听事件
使用 $emit(eventName) 触发事件
另外,父组件可以在使用子组件的地方直接用 v-on 来监听子组件触发的事件。
代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.2/vue.min.js"></script>
</head>
<body>
<div id="app">
<div id="counter-event-example">
<p>{{ total }}</p>
<button-counter v-on:increment="incrementTotal"></button-counter>
<button-counter v-on:increment="incrementTotal"></button-counter>
</div>
</div>
<script>
Vue.component('button-counter', {
template: '<button v-on:click="incrementHandler">{{ counter }}</button>',
data: function () {
return {
counter: 0
}
},
methods: {
incrementHandler: function () {
this.counter += 1
this.$emit('increment')
}
},
})
new Vue({
el: '#counter-event-example',
data: {
total: 0
},
methods: {
incrementTotal: function () {
this.total += 1
}
}
})
</script>
</body>
</html>
展示:
2.Vue.js 自定义指令
知识点1:
除了默认设置的核心指令( v-model 和 v-show ), Vue 也允许注册自定义指令。
代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.2/vue.min.js"></script>
</head>
<body>
<div id="app">
<p>自动获取焦点</p>
<input v-focus>
</div>
<script>
// 注册一个全局自定义指令 v-focus
Vue.directive('focus', {
// 当绑定元素插入到 DOM 中。
inserted: function (el) {
// 聚焦元素
el.focus()
}
})
// 创建根实例
new Vue({
el: '#app'
})
</script>
</body>
</html>
展示:
知识点2:
钩子函数
钩子函数的参数有:
el: 指令所绑定的元素,可以用来直接操作 DOM。
binding: 一个对象,包含以下属性:
name: 指令名,不包括 v- 前缀。
value: 指令的绑定值,例如:v-my-directive=“1 + 1”,value 的值是 2。
oldValue: 指令绑定的前一个值,仅在 update 和 componentUpdated 钩子中可用。无论值是否改变都可用。
expression: 绑定值的表达式或变量名。例如 v-my-directive=“1 + 1” ,expression 的值是 “1 + 1”。
arg: 传给指令的参数。例如 v-my-directive:foo,arg 的值是 “foo”。
modifiers: 一个包含修饰符的对象。例如:v-my-directive.foo.bar,修饰符对象 modifiers 的值是 { foo: true,bar: true }。
vnode: Vue 编译生成的虚拟节点。
oldVnode: 上一个虚拟节点,仅在 update 和 componentUpdated 钩子中可用。
代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
</head>
<body>
<div id="container">
<h2>{{msg}}</h2>
<button @click="add" style="font-size: large;">点击</button>
<p v-change="handleClick">hello world!</p>
</div>
<script>
new Vue({
el:'#container',
data:{
msg:'hello',
color:['orange','yellow','red','pink'],
order:0
},
methods:{
add:function(){
this.order++;
},
handleClick:function(){
if(this.order==this.color.length){
this.order=0;
}
return this.color[this.order];
}
},
directives:{
change:{
bind:function(el,bindings){
el.style.backgroundColor=bindings.value();
},
update:function(el,bindings){
el.style.backgroundColor=bindings.value();
},
}
}
})
</script>
</body>
</html>
展示:
点击后可以改变颜色