1. 程式人生 > >解決使用vue.js與ckeditor.js時,ckeditor不顯示問題

解決使用vue.js與ckeditor.js時,ckeditor不顯示問題

我們都知道在vue2.js中新增了虛擬dom 

這裡是我的js程式碼:

var vm1 = new Vue({
el : '.myfrom',
data : {
items : []
},
created : function(){
$.post("/island/admin/queryOneNewsById.do",{"id":parseInt(id)},function(data){
vm1.items = data;
/*Vue.nextTick(function () {
CKEDITOR.replace('editor01');
       });*/
});//end post
}
})

這裡是我的html程式碼 : 

<form class="myfrom" enctype="multipart/form-data" method="post"
action="/island/admin/reviseOneNews.do">
<legend>前臺小視窗</legend>
<input type="hidden" value="items.id" id="news_id" name="id">
<div class="form-group">
<label>新聞標題</label> <input type="text" class="form-control"
id="news_title" name="title" placeholder="請輸入新聞標題"
v-text="items.title">
</div>


<div class="form-group">
<label>新聞封面內容</label>
<textarea class="form-control" rows="3" name="covercontent"
placeholder="請輸入新聞封面內容" id="news_covercontent">{{items.covercontent}}</textarea>
</div>


<div class="form-group">
<label>作者</label>
<textarea class="form-control" rows="1" name="author"
placeholder="請輸入作者姓名" id="news_author">{{items.author}}</textarea>
</div>


<div class="form-group">
<label>請選擇新聞封面</label><br>
<div class="uploader green">
<input type="text" class="filename" readonly /> <input
type="button" name="file" class="button" value="Browse..." /> <input
type="file" size="30" name="file" />
</div>
</div>


<div class="form-group">
<label>新聞內容</label><br>
<textarea rows="30" cols="50" name="editor01" id="editor" v-text="items.content">請輸入...</textarea>
</div>


<button type="button" class="btn btn-default revisenews_btn"
style="float:right;width:100px;margin-top:10px;">提交</button>
</form>

第一次我在使用的時候 是吧 CKEDITOR.replace('editor01'); 這裡的editor01是textarea中的name名,我把ckeditor的初始化放在了vue初始化的前面 ,這裡就會出現錯誤,而放在後面則不會 原因就是當vue.js初始化的時候 el 是一個容器 而且此時會把el下的所有元素作為虛擬dom放在記憶體中 也就是這個時候 頁面中是不存在這個表單的  而我們把ckeditor的初始化放在前面就會出錯(因為你在初始化一個根本不存在的節點)  

這裡推薦一種做法 :

Vue.nextTick(function () {
CKEDITOR.replace('editor01');
       });

將此程式碼放入created方法中

這樣做後仍然可能會不管用  請清理快取 伺服器上的快取清理乾淨 瀏覽器快取清理 再開啟即可

這裡還有一個需要注意的是  我的jquery中有對vue.js渲染的dom部分進行dom節點操作  但是這部分等於是後來通過jquery的方式新增(動態載入)  所以需要使用on方法進行資料繫結

示例程式碼如下

//顯示上傳圖片名字(前臺上傳按鈕樣式)
$(document).on("change","input[type=file]",function(){
$(this).parents(".uploader").find(".filename").val($(this).val().substring(12,$(this).val().length));
})
$(document).on("each","input[type=file]",function(){
if($(this).val()==""){$(this).parents(".uploader").find(".filename").val("您還沒有選擇封面圖片...");}
})