话不多说,先来一个小提醒:需要将node升级到较高版本(建议12+),否则你可能会遇到一些问题。官方推荐使用vscode编辑器和Volar拓展,使用时记得先把Vetur禁用掉,不然还是会有一堆报红提示。
- 创建项目
npm init vite hello-vue3 -- -- template vue
通过方向键选择所要创建项目的框架(vue、react等等)。
cd进hello-vue3,启动项目npm run dev
,创建好的项目结构如下图:
- 生成的HelloWorld组件的JavaScript:
可以看到:默认配置了ts,没有export default,setup放置在script标签内,引入的组件不需要手动注册,定义的属性和方法也不需要return出去。setup语法糖向模板公开了所有的顶级绑定;
-
关于defineProps
更多信息参见:https://v3.cn.vuejs.org/api/sfc-script-setup.html#%E4%BD%BF%E7%94%A8%E7%BB%84%E4%BB%B6
壳子搭好了,把样式搞搞:
- 使用scss
安装:cnpm install sass --save
在assets下创建scss文件public.scss,并添加配置:
这样就可以在全局下正常使用scss了。注意尾巴的分号,不要漏掉哦!
- 使用路由:vue-router@4
注意:vue3是要搭配路由4的哦!
安装:cnpm install vue-router@4 --save
路由的创建方式和vue2略有区别,vue2使用new Router()的方式,而vue3使用的是createRouter:
import { createRouter, createWebHistory, createWebHashHistory} from 'vue-router'
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About },
]
const router = createRouter({
history: createWebHashHistory(),//或createWebHistory
routes: routes
})
export default router;
在app.vue组件中放置:<router-view></router-view>
使用过程中组件无法显示,提示如下:
解释:组件提供模板选项,但是在Vue的这个构建中不支持运行时编译,配置你的bundler别名 vue: vue/dist/vue.esm-bundler.js。
解决方法: 在根目录下的配置文件vite.config.ts中添加alias别名设置:
alias:{
'vue': 'vue/dist/vue.esm-bundler.js'
}
添加完成后终端上会有如下提示:
但是组件可以正常显示,路由也可以使用。 将alias放在resolve里就不会报这个提示了。即:
resolve:{
alias: {
'vue': 'vue/dist/vue.esm-bundler.js'
}
}
此时完整的配置文件如下:
- this问题
在使用路由跳转的过程中遇到了this的问题:vue3组件中的this和vue2已经不一样了,详情可以到官网看。这里说下解决方法:
import { getCurrentInstance } from 'vue'
const {proxy} = (getCurrentInstance() as any) //如果是js可以直接const {proxy} = getCurrentInstance();
const _this = proxy;//可在控制台打印_this,会发现和vue2中的this一样
- 全局变量
最后说一下全局变量,这个也是日常开发中最常使用的:
设置:app.config.globalProperties.name = "全局变量";
在组件中使用:
import {getCurrentInstance} from 'vue'
const {proxy} = (getCurrentInstance() as any)
console.log(proxy.name);
到这里,基本的东西都有啦,后续再更新!