vue3.x起步
- 前端
- 三生万物
- 0
vue3.0现在还是beta版本,最好不要用于生产,不过可以试先尝尝鲜,看看是什么样的
vue3.0主要有以下新特性
- Performance(性能比2.x更好)
- Tree-shaking support(打包时可以把无用的模板去掉)
- Composition API(组合API)
- Fragment、Teleport、Suspense(碎片、通信、悬念)
- Better TypeScript support(更好的支持TS)
- Custom Renderer API(自定义渲染API)
从上可以看出在3.0的版本上,尤大大还是做了很多功夫的
一、安装
安装3.0版本,需要把vue-cli升级一下,这里直接重新安装就行了
> npm install -g @vue/cli
> vue -V
@vue/cli 4.4.6
然后创建项目
> vue create vue-next-test
是使用默认还是自定义,看自己需求了,这里建议使用Manualy select features,可以试先把Vuex和Router集成进来,不急着使用TypeScript模式
项目创建完成后,然后进入最重要的一步,安装vue-next扩展,vue-next会把项目改造成3.0的模式
vue-next-test> vue add vue-next
安装完成后,就可以在项目里使用vue3.0的新特性了,是不是很激动,下面来介绍下有哪些新写法
二、新写法
进入main.js会看到以下代码
import { createApp } from 'vue';
import App from './App.vue'
import router from './router'
import store from './store'
createApp(App).use(router).use(store).mount('#app')
这里不直接new Vue了,而是暴露了一个createApp方法来创建vue实例,然后对use进行了扩展,通过use方法对router和vuex进行链式加载,还是挺新颖的
然后看下路由有哪些改动,代码如下:
import { createRouter, createWebHistory } from 'vue-router';
import Home from '../views/Home.vue'
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/about',
name: 'About',
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
}
]
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes
})
export default router
从上可以看出,vue-router也是通过暴露方法来创建的,是和vue类似的改造,但vuex的使用方式和以前一样没有改变
import Vuex from 'vuex'
export default Vuex.createStore({
state: {
},
mutations: {
},
actions: {
},
modules: {
}
});
不过组件中的引入方式可能发生了变化,但这个不好明确,因为beta不稳定
三、提供了类似React Hook的实现
<template>
<div>
<h1>test count: {{count}}</h1>
<button type="button" @click="count++">递增</button>
<button type="button" @click="decrement">递减</button>
</div>
</template>
<script>
import { ref } from "vue";
export default {
setup() {
const count = ref(0);
const decrement = () => {
count.value--;
}
return {
count,
decrement
};
}
};
</script>
直接暴露了一个setup方法,然后一些实现方式也有所改变,如上面的递增和递减
最后由于不同时间创建的项目及实现方式都不一样,所以这里就先介绍到这里,不过不用在意这些细节,毕竟只是先尝尝鲜,当然vue3.0能否正式发布还要期待,不过也有跳票的可能
免责申明:本站发布的内容(图片、视频和文字)以转载和分享为主,文章观点不代表本站立场,如涉及侵权请联系站长邮箱:xbc-online@qq.com进行反馈,一经查实,将立刻删除涉嫌侵权内容。