说明
【Vue 开发实战】学习笔记。
内置指令
指令就是一个语法糖,说白了就是一个标志位,从 template 编译到 render 函数的时候,会将语法糖编译成 js 代码。
<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>
自定义指令
<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>
点击按钮加一
销毁: