0%

vue3 与 vite

vue3 与 vite

vue 2.x 与 vue 3.x

2.x 时代的 Vue 没有“应用”的概念,所谓的应用只是一个 Vue 的根实例 new Vue() 。
当我们需要修改一些全局属性的时候,只能通过 Vue 对象本身来修改,比如:

1
2
3
4
5
6
// 2.x 时代的全局属性
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
// 3.x createApp
const foo = createApp(Foo);
foo.directive('focus' /* ... */);
const bar = createApp(Bar);
bar.directive('focus' /* ... */);
// foo 和 bar 都具备了 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')

// foo 和 bar 会具备同一个 focus 指令

使用 Vite 构建项目

除了上面的 Vue CLI 创建项目之外,Vue 3.x 还可以通过新工具 Vite 创建项目。
Vite 是一个由原生 ES 模块驱动的 Web 开发构建工具,支持模块热更新和按需加载。

补充

Vue.directive()的用法和实例

指令定义函数提供了几个钩子函数(可选):

  1. bind: 只调用一次,指令第一次绑定到元素时调用,用这个钩子函数可以定义一个在绑定时执行一次的初始化动作。
  2. inserted: 被绑定元素插入父节点时调用(父节点存在即可调用,不必存在于 document 中)。
  3. update: 被绑定元素所在的模板更新时调用,而不论绑定值是否变化。通过比较更新前后的绑定值,可以忽略不必要的模板更新(详细的钩子函数参数见下)。
  4. componentUpdated: 被绑定元素所在模板完成一次更新周期时调用。
  5. 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
//注册一个全局自定义指令 v-focus
Vue.directive('focus', {
//当绑定元素插入到DOM中。
inserted: fuction(el, binding) {
//聚焦元素
el.focus();
}
})

new Vue({
el: '#app'
})
  • 一个拖拽的demo
  1. 被拖拽的元素必须用position定位,才能被拖动;
  2. 自定义指令完成后需要实例化Vue,挂载元素;
  3. 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

  • 本文作者: David Xue
  • 本文链接: https://xdw-h.github.io/11/
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!