2020 年 04 月 17 日,尤小右微博发布 Vue 3.0 beta 了!
看到的第一眼也是觉得学不动了!第二天,真香~所以本 Chat 简单分享下我的体验。
序2020 年 4 月 17 日凌晨 vue3.0 beta 了。
项目初始化 安装 vue-clinpm install -g @vue/cli
安装完使用vue -V
可以看到我的版本是@vue/cli 4.3.1
的,cli 版本只要在 3.x 以上即可。
vue create vue-3.0.0-beta.1-demo
输入完命令会出现交互的弹窗,我一次选的是:
Manually select features
- 第二项我勾选了 Babel、Router、CSS Pre-processors、Vuex、Linter/Formatter后面根据大家的需求都是些 Y/N 的选项可自己选择下。最后回车后自动安装依赖,我在这里就卡到下面这个界面了。
卡在这里我一开始以为是没有使用淘宝源所以很慢,所以为了加快安装依赖,我使用淘宝源加快初始化项目。
vue create -r https://registry.npm.taobao.org vue-3.0.0-beta.1-demo
结果还是卡在这里不动,所以排除 npm 源的问题,于是又看了下我的 node 版本node/12.16.2
,于是通过 node 版本管理器 n 切换到node/10.20.1
,重新尝试初始化项目,很快项目就创建完毕了。
由于 vue-cli 没有直接支持创建 3.0 项目,所以需要通过插件升级,我们输入指令:
vue add vue-next
安装完成后会发现 vue 的版本已经是3.0.0-beta.1
,vue-router 和 vuex 也都升级到 4.0 的版本。
npm run serve
3.0 初体验
首先创建个页面路由,和 2.x 并无差别。
{ path: '/test', name: 'test', component: () => import(/* webpackChunkName: "about" */ '../views/test.vue')}
然后在test.vue
里面把官网给的基本示例拿过来
Count is: {{ state.count }}, double is: {{ state.double }} import { ref, reactive, computed, watch, onMounted, onUpdated, onUnmounted, getCurrentInstance } from 'vue'export default { setup() { const state = reactive({ count: 0, double: computed(() => state.count * 2) }) const { ctx } = getCurrentInstance() console.log(ctx.$router.currentRoute) const userName = computed(()=>ctx.$store.state.userName) console.log(userName) function increment() { state.count++ } watch(() => state.count, val=>{ console.log(`watch:${val}`) }) onMounted(()=>{ console.log('mounted') console.log(root.value) }) onUpdated(()=>{ console.log('updated') }) onUnmounted(()=>{ console.log('unmounted') }) return { state, increment, root } }}
setup
- 调用时间:创建组件实例时,在初始道具解析后立即调用。在生命周期方面,它在 beforeCreate 挂接之前被调用。
- 模板使用:可以看到
setup
返回的 state 对象和方法被合并到组件模板的渲染上下文中
代码中可以看到计算属性 computed 是一个方法,里面包含了一个回调函数,当计算属性返回结果是会自动获取返回的结果
watch同样也是一个方法,它包含两个参数,第一个参数是要监听的值,第二个是触发监听器的回调函数。
生命周期官网给出的 2.X 生命周期和 Composition API 之间的映射:
- ~~beforeCreate~~ ->使用 setup()
- ~~created~~ ->使用 setup()
- beforeMount -> onBeforeMount
- mounted -> onMounted
- beforeUpdate -> onBeforeUpdate
- updated -> onUpdated
- beforeDestroy -> onBeforeUnmount
- destroyed -> onUnmounted
- errorCaptured -> onErrorCaptured
上面例子中,我用了getCurrentInstance
获取了当前组件的实例,然后ctx
获取当前实例的上下文,ctx.$router
拿到Vue Route 实例,里面的 currentRoute 里有当前路由的信息。
- 首先定义 vuex 和之前并无差别,在 src/store/index.js 中定义
import Vuex from 'vuex'export default Vuex.createStore({ state: { userName: 'zack' }, mutations: { setUserName(state, value){ state.userName = value } }, actions: { }, modules: { }});
- 在 test.vue 使用 vuex 中定义的 userName,通过计算属性
computed
和当前实例ctx
可以获取到 vuex 中定义的 userName
const userName = computed(()=>ctx.$store.state.userName)
- 更新 vuex 状态也是和之前一样使用
commit
去更新
ctx.$store.commit('setUserName', 'zengkaiz')
阅读全文: http://gitbook.cn/gitchat/activity/5e9eac0207428647e94af70b
您还可以下载 CSDN 旗下精品原创内容社区 GitChat App ,阅读更多 GitChat 专享技术内容哦。