# vue hook 使って vuejs コンポーネントライフサイクル監視
この記事を見て勉強になりました。v-runtime-template (opens new window)というコンポーネント紹介されました。記事を読んで vue の hook 機能は面白いなあと思いました。
Listen to lifecycle hooks on third-party Vue.js components (opens new window)
v-runtime-template (opens new window)
A Vue.js components that makes easy compiling and interpreting a Vue.js template at runtime by using a v-html like API.
API のような v-html を使用して、実行時に Vue.js テンプレートを簡単にコンパイルおよび解釈できる Vue.js コンポーネント。
main.vue
<template>
<div id="app">
Hi fly! Check out the console and the code around!
<Child @hook:mounted="childMounted"/>
</div>
</template>
<script>
import Child from "./Child";
export default {
name: "app",
components: { Child },
methods: {
childMounted() {
console.log("Child was mounted");
}
}
};
</script>
Child.vue
<template>
<h3></h3>
</template>
結果
console.log 出力される
Child was mounted
# vue-hooks
vue-hooks (opens new window)0.3.2 バージョンは npm に公開されていますが、週間ダウンロードがまだ少ないようです。正式バージョンではないので、evan さんもプロダクトに使わないように呼びかけています。
# API の種類
- withHooks
- useData
- useComputed
- useWatch
- useMounted
- useUpdated
- useDestroyed
# 使い方
import { hooks, useData, useComputed } from "vue-hooks";
Vue.use(hooks);
new Vue({
template: `
<div @click="data.count++">
{{ data.count }} {{ double }}
</div>
`,
hooks() {
const data = useData({
count: 0
});
const double = useComputed(() => data.count * 2);
return {
data,
double
};
}
});
# サンプル
import Vue from "vue";
import { withHooks, useState, useEffect } from "vue-hooks";
// a custom hook...
function useWindowWidth() {
const [width, setWidth] = useState(window.innerWidth);
const handleResize = () => {
setWidth(window.innerWidth);
};
useEffect(() => {
window.addEventListener("resize", handleResize);
return () => {
window.removeEventListener("resize", handleResize);
};
}, []);
return width;
}
const Foo = withHooks(h => {
// state
const [count, setCount] = useState(0);
// effect
useEffect(() => {
document.title = "count is " + count;
});
// custom hook
const width = useWindowWidth();
return h("div", [
h("span", `count is: ${count}`),
h(
"button",
{
on: {
click: () => setCount(count + 1)
}
},
"+"
),
h("div", `window width is: ${width}`)
]);
});
// just so you know this is Vue...
new Vue({
el: "#app",
render(h) {
return h("div", [h(Foo), h(Foo)]);
}
});