Skip to content

Instantly share code, notes, and snippets.

@lipengzhou
Last active March 12, 2019 08:38
Show Gist options
  • Save lipengzhou/414520bb09d5c826150d19af4a5d9098 to your computer and use it in GitHub Desktop.
Save lipengzhou/414520bb09d5c826150d19af4a5d9098 to your computer and use it in GitHub Desktop.
模拟的v-if内部原理
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Vue 自定义指令模拟v-if</title>
<style>
.box {
width: 100px;
height: 100px;
background-color: #f40;
}
</style>
</head>
<body>
<div id="app">
<h1>{{ message }}</h1>
<input type="checkbox" v-model="seen">
<div class="box" v-my-if="seen"></div>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script>
const myIf = {
parentEl: null,
commentEl: null,
install(Vue, options) {
const plugin = this
Vue.directive('my-if', {
inserted(el, binding) {
plugin.parentEl = el.parentElement
if (!binding.value) {
plugin.commentEl = document.createComment(' ')
plugin.parentEl.replaceChild(plugin.commentEl, el)
}
},
update(el, binding) {
if (binding.value) {
plugin.parentEl.replaceChild(el, plugin.commentEl)
} else {
plugin.parentEl.replaceChild(plugin.commentEl, el)
}
}
})
}
}
Vue.use(myIf)
const app = new Vue({
el: '#app',
data: {
message: 'Hello Vue.js!',
seen: false
},
methods: {}
})
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment