vue3 与 vite
vue 2.x 与 vue 3.x
2.x 时代的 Vue 没有“应用”的概念,所谓的应用只是一个 Vue 的根实例 new Vue() 。
当我们需要修改一些全局属性的时候,只能通过 Vue 对象本身来修改,比如:
1 2 3 4 5 6
| Vue.prototype.$http = axios; Vue.directive('focus', { inserted: el => el.focus() }); Vue.config.errorHandler = errorHandler;
|
这样的行为会污染 Vue 对象,导致从同一个 Vue 创建的实例会共享相同的全局配置
而通过 createApp 返回的是独立的实例,修改该实例的属性不会影响其他 createApp 创建的实例:
1 2 3 4 5 6
| const foo = createApp(Foo); foo.directive('focus' ); const bar = createApp(Bar); bar.directive('focus' );
|
如果确实需要两个应用共享配置,还可以通过 createApp 创建一个工厂函数:
1 2 3 4 5 6 7 8 9 10
| const createMyApp = options => { const app = createApp(options) app.directive('focus' ) return app }
const foo = createMyApp(Foo).mount('#foo') const bar = createMyApp(Bar).mount('#bar')
|
使用 Vite 构建项目
除了上面的 Vue CLI 创建项目之外,Vue 3.x 还可以通过新工具 Vite 创建项目。
Vite 是一个由原生 ES 模块驱动的 Web 开发构建工具,支持模块热更新和按需加载。
补充
Vue.directive()的用法和实例
指令定义函数提供了几个钩子函数(可选):
- bind: 只调用一次,指令第一次绑定到元素时调用,用这个钩子函数可以定义一个在绑定时执行一次的初始化动作。
- inserted: 被绑定元素插入父节点时调用(父节点存在即可调用,不必存在于 document 中)。
- update: 被绑定元素所在的模板更新时调用,而不论绑定值是否变化。通过比较更新前后的绑定值,可以忽略不必要的模板更新(详细的钩子函数参数见下)。
- componentUpdated: 被绑定元素所在模板完成一次更新周期时调用。
- unbind: 只调用一次, 指令与元素解绑时调用。
- 官网demo,刷新页面input自动获取焦点
1 2 3
| <div id="app"> <input type="text" v-focus /> </div>
|
1 2 3 4 5 6 7 8 9 10 11 12
| Vue.directive('focus', { inserted: fuction(el, binding) { el.focus(); } })
new Vue({ el: '#app' })
|
- 被拖拽的元素必须用position定位,才能被拖动;
- 自定义指令完成后需要实例化Vue,挂载元素;
- inserted: 被绑定元素插入父节点时调用(父节点存在即可调用,不必存在于 document 中)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| <style type="text/css"> .one,.two{ height:100px; width:100px; border:1px solid #000; position: absolute; -webkit-user-select: none; -ms-user-select: none; -moz-user-select: -moz-none; cursor: pointer; } .two{ left:200px; } </style> <div id="app"> <div class="one" v-drag>拖拽one</div> <div class="two" v-drag>拖拽two</div> </div>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| Vue.directive('drag', { inserted:function(el){ el.οnmοusedοwn=function(e){ let l=e.clientX-el.offsetLeft; let t=e.clientY-el.offsetTop; document.οnmοusemοve=function(e){ el.style.left=e.clientX-l+'px'; el.style.top=e.clientY-t+'px'; }; el.οnmοuseup=function(){ document.οnmοusemοve=null; el.οnmοuseup=null; } } } }) new Vue({ el:'#app' });
|
转发:https://www.cnblogs.com/wisewrong/p/13717287.html