前提・実現したいこと
書籍のvuejsのディレクティブサンプルコードが動かない状態です。
発生している問題・エラーメッセージ
デベロッパーツールのコンソールに表示されるエラーになります。
[Vue warn]: Error in directive my-directive bind hook: "TypeError: Cannot set property 'innerHTML' of undefined" vue.js:1841 TypeError: Cannot set property 'innerHTML' of undefined
フォームに入力してクリックをすると以下の部分が増えていきます。
[Vue warn]: Error in directive my-directive bind hook: "TypeError: Cannot set property 'innerHTML' of undefined"
該当のソースコード
directive.js
1Vue.directive('my-directive', { 2 bind: function(){ 3 this.el.innerHTML = '<p>**bind now**</p>'; 4 }, 5 update: function (newValue, oldValue) { 6 this.el.innerHTML = '<p>' + oldValue + ' → ' + newValue + '</p>'; 7 }, 8 unbind: function(){ 9 this.el.innerHTML = '<p>**unbind**</p>'; 10 }, 11}); 12 13function initial(){ 14 15 new Vue({ 16 el: '#msg', 17 data: { 18 val:'', 19 message:'this is message!' 20 }, 21 methods: { 22 myfunc:function() { 23 this.message = this.val; 24 } 25 } 26 }); 27}
directive.html
1<!doctype html> 2<html lang="ja"> 3<head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" 6 content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> 7 <meta http-equiv="X-UA-Compatible" content="ie=edge"> 8 <title>vue-lessons</title> 9 <script src="https://npmcdn.com/vue/dist/vue.js"></script> 10 <script src="js4-36.js"></script> 11 <link rel="stylesheet" href="style.css"> 12</head> 13<body onload="initial();"> 14<h1>Vue.js</h1> 15<div id="msg"> 16 17 <div v-my-directive="message">ok.</div> 18 19 <input type="text" v-model="val"> 20 <input type="button" v-on:click="myfunc();" value="click"> 21</div> 22</body> 23</html>
試したこと1
this.el.innerHTMLをthis.elとしてみたら
デベロッパーツールのエラーは消え、ideでもelの部分が紫になりましたが
DOM要素が書き変わるという動作はしませんでした。
試したこと2
<div v-my-directive="message">ok.</div> ↓ <div v-my-directive="message"><p>ok.</p></div>としてみましたが変化ありませんでした。
他に試すべきことなどご教授いただけましたら幸いです。
よろしくお願いいたします。
回答2件
あなたの回答
tips
プレビュー