vue3.0项目初始化
vue create vue-next-test
升级vue3.0项目
cd vue-next-test
vue add vue-next
执行上述指令后,会自动安装 vue-cli-plugin-vue-next 插件(查看项目代码),该插件会完成以下操作:
安装 Vue 3.0 依赖
更新 Vue 3.0 webpack loader 配置,使其能够支持 .vue 文件构建(这点非常重要)
创建 Vue 3.0 的模板代码
自动将代码中的 Vue Router 和 Vuex 升级到 4.0 版本,如果未安装则不会升级
自动生成 Vue Router 和 Vuex 模板代码
vue3.0项目初始化
main.js 引用所需的api即可
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')
router/index.vue
import {
createRouter, createWebHashHistory } 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: createWebHashHistory(),
routes
})
export default router
vue3.0中废弃了filter过滤器
vue3.0中的新特性 composition-api
test.vue
<script>
import {
reactive,watchEffect} from 'vue'
// 类似 react hooks中的useState
const state = reactive({
count:1
})
const increment = () => {
state.count++
}
// 类似react hooks 中的 useEffect
watchEffect(() => {
document.body.innerHTML = `count: ${
state.count}`
})
document.body.addEventListener('click',function () {
increment()
})
</script>
结合vue使用
<template>
<button @click="increment">{
{
state.count}}</button>
</template>
<script>
import {
reactive} from 'vue'
// 类似react hooks 中的 useEffect
// watchEffect(() => {
// document.body.innerHTML = `count: ${state.count}`
// })
// document.body.addEventListener('click',function () {
// increment()
// })
export default {
setup() {
// 类似 react hooks中的useState
const state = reactive({
count:1
})
const increment = () => {
state.count++
}
return {
state,
increment
}
}
}
</script>
其次,还可以将js内容抽离出来封装,在test.vue中引入即可
useTest.js
import {
reactive ,computed ,watch ,onMounted} from "vue";
export default function useTest () {
// 类似 react hooks中的useState
const state = reactive({
count:1
})
const increment = () => {
state.count++
}
const doubleCount = computed(() =>state.count*2)
watch