1. 应用创建
createApp(App)
.use(router)
.use(vuex)
.use(ElementPlus)
.mount('#app')
2. router的使用
// router.js
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import Home from '../views/Home.vue'
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
]
const router = createRouter({
// createWebHistory 创建history模式,createWebHashHistory 创建hash模式
history: createWebHistory(process.env.BASE_URL),
routes
})
export default router
// main.js
import router from './router'
createApp(App)
.use(router)
.mount('#app')
3. vuex的使用
// store.js
import {createStore} from 'vuex'
export defalut const store = createStore({
state: {},
getters: {},
mutations: {}
...
})
// main.js
import store from './store'
createApp(App)
.use(store)
.mount('#app')
以上vue2和vue3的差别就在于插件的注册和使用。这种通过export,import 导出api 的做法支持了webpack的tree shaking,打包时去除无用的代码,减少打包之后项目的体积。
来了解一下,vue的use()方法
vue2源码
function initUse (Vue) {
Vue.use = function (plugin) {
var installedPlugins = (this._installedPlugins || (this._installedPlugins = []));
if (installedPlugins.indexOf(plugin) > -1) {
return this
}
// additional parameters
var args = toArray(arguments, 1);
args.unshift(this);
if (typeof plugin.install === 'function') {
plugin.install.apply(plugin, args);
} else if (typeof plugin === 'function') {
plugin.apply(null, args);
}
installedPlugins.push(plugin);
return this
};
}
从上面可以知道vue2的插件通过 plugin.install.apply(plugin, args) 注入vue实例。
vue3的源码:
// 在createApp()方法中...
const app = (context.app = {
...
use(plugin, ...options) {
if (installedPlugins.has(plugin)) {
warn$1(`Plugin has already been applied to target app.`);
}
else if (plugin && isFunction(plugin.install)) {
installedPlugins.add(plugin);
plugin.install(app, ...options);
}
else if (isFunction(plugin)) {
installedPlugins.add(plugin);
plugin(app, ...options);
}
else {
warn$1(`A plugin must either be a function or an object with an "install" ` +
`function.`);
}
return app;
},
},
...
以上得知:plugin.install(app, …options)把app传入了install方法,无需在使用时另外传递实例了。
4. vue3新特性
- 双向数据绑定原理变化:vue2依赖Object.defineproperty()进行数据劫持,vue3使用Proxy()进行数据代理。
- 组合式 API
- 生命周期函数
- Teleport : 允许我们控制在 DOM 中哪个父节点下渲染 HTML
- 支持多根节点的组件,也就是template下面不用包裹一层div了,可以加多个块, 叫做片段
- 触发组件选项(emit 事件选项, 自定义v-model等)
- 单文件组件组合式 API setup
- 单文件组件状态驱动的 CSS 变量
- SFC (style scoped) 现在可以包含全局规则或只针对插槽内容的规则
- Suspense 异步组件(实验性)
- 透传attributes