在vue中引入joint.js的問題,以前在網上搜了不少,都沒有給出一個確切的答案,搗鼓了兩天終於弄明白了,作個記錄。
首先,我參考了一篇來自stackoverflow的文章點我點我
看完這篇文章,你們應該至少大體怎麼作了,下面咱們來具體看一下:css
npm install jointjs --save
window.$ = require('jquery');
window.joint = require('jointjs');vue
這裏須要注意的是,joint.js依賴backbone、jquery和lodash,在經過script方式引入時,須要一一引入這些文件,但經過vue的npm時不須要,npm引入的joint.js已經默認封裝好了這些。
經過這樣引入還不夠,可能會遇到圖能夠正常加載,但沒法拖拽的問題,遇到這些問題通常是joint.js和本身vue項目中的環境衝突了,致使沒法讀取或者讀取錯誤。jquery
我原來的項目中安裝了element、iview、axios、vuex、jquery,再安裝joint.js後,jointjs沒法正常加載,後來從新建了一個項目,只安裝了element、axios、vuex,爲避免jquery和joint.js中的jquery衝突,後來沒有裝jquery。
這樣就好了麼?就能夠運行上文連接中的例子了麼?像這樣:webpack
<template> <div> <h1>Home</h1> <div id="myholder"></div> </div> </template> <script> export default { created() { let graph = new joint.dia.Graph; let paper = new joint.dia.Paper({ el: $('#myholder'), width: 600, height: 200, model: graph, gridSize: 1 }); let rect = new joint.shapes.basic.Rect({ position: { x: 100, y: 30 }, size: { width: 100, height: 30 }, attrs: { rect: { fill: 'blue' }, text: { text: 'my box', fill: 'white' } } }); let rect2 = rect.clone(); rect2.translate(300); let link = new joint.dia.Link({ source: { id: rect.id }, target: { id: rect2.id } }); graph.addCells([rect, rect2, link]); } } </script>
NoNoNo,注意到這裏是把渲染放在了created的生命週期裏,根據vue的生命週期,是沒法找到joint的掛載div的el: $('#myholder')
,也就是說,運行會報錯,個人解決方法是把div放了一個click,把joint的內容從created中拿出,放在methods中,須要點擊一下才可顯示哦,還不太完美,以待改進(~ ̄▽ ̄)~
也就是說,代碼會變成這樣:ios
<template> <div> <div id="myholder" @click="click_joint"></div> </div> </template> <script> export default { methods:{ click_joint() { let graph = new joint.dia.Graph; let paper = new joint.dia.Paper({ el: $('#myholder'), width: 600, height: 200, model: graph, gridSize: 1 }); let rect = new joint.shapes.basic.Rect({ position: { x: 100, y: 30 }, size: { width: 100, height: 30 }, attrs: { rect: { fill: 'blue' }, text: { text: 'my box', fill: 'white' } } }); let rect2 = rect.clone(); rect2.translate(300); let link = new joint.dia.Link({ source: { id: rect.id }, target: { id: rect2.id } }); graph.addCells([rect, rect2, link]); } } } </script>
點明一下,經過npm引入只要install jointjs就能夠,不須要install lodash、backbone、jquery,也不須要在頁面中導入joint.css文件。筆者以前經過script方式引入joint.js,試了不少次,都沒有成功,一直讀取joint.js文件出錯,若是其餘小夥伴嘗試成功,歡迎交流分享。web