指令
内置指令,语法糖、标志位
v-text
替换文本v-html
替换HTMLv-show
切换显示隐藏v-if
v-else
v-else-if
条件判断v-for
循环v-on
绑定变量或表达式,简写如::class="class_name"v-bind
绑定事件,简写如:@click="handleClick"v-model
双向绑定v-slot
插槽v-pre
转义,让 `` 直接输出v-cloak
基本用不到v-once
绑定的变量只执行一次
<template>
<div>
<h2>v-text</h2>
<div v-text="'hello vue'">hello world</div>
<h2>v-html</h2>
<div v-html="'<span style="color: red">hello vue</span>'">
hello world
</div>
<h2>v-show</h2>
<div v-show="show">hello vue</div>
<button @click="show = !show">change show</button>
<h2>v-if v-esle-if v-else</h2>
<div v-if="number === 1">hello vue {{ number }}</div>
<div v-else-if="number === 2">hello world {{ number }}</div>
<div v-else>hello geektime {{ number }}</div>
<h2>v-for v-bind</h2>
<div v-for="num in [1, 2, 3]" v-bind:key="num">hello vue {{ num }}</div>
<h2>v-on</h2>
<button v-on:click="number = number + 1">number++</button>
<h2>v-model</h2>
<input v-model="message" />
<h2>v-pre</h2>
<div v-pre>{{ this will not be compiled }}</div>
<h2>v-once</h2>
<div v-once>
{{ number }}
</div>
</div>
</template>
<script>
export default {
data: function() {
this.log = window.console.log;
return {
show: true,
number: 1,
message: "hello"
};
}
};
</script>
自定义指令
vue给我们暴露了5个生命周期钩子函数
- bind
- inserted
- update
- componentUpdated
- unbind
v-append-text 自定义指令
<template>
<div>
<button @click="show = !show">
销毁
</button>
<button v-if="show" v-append-text="`hello ${number}`" @click="number++">
按钮
</button>
</div>
</template>
<script>
export default {
directives: {
appendText: {
bind() {
console.log("bind");
},
inserted(el, binding) {
el.appendChild(document.createTextNode(binding.value));
console.log("inserted", el, binding);
},
update() {
console.log("update");
},
componentUpdated(el, binding) {
el.removeChild(el.childNodes[el.childNodes.length - 1]);
el.appendChild(document.createTextNode(binding.value));
console.log("componentUpdated");
},
unbind() {
console.log("unbind");
}
}
},
data() {
return {
number: 1,
show: true
};
}
};
</script>