本篇介绍 10 点如何从实战中学习突破 Vue JS 3 的新特性,细细看完,必定会有收获~html
主体译自:【Vue JS 3 — The Practical Guide】vue
更多学习资料:【https://github.com/Jerga99/vue-3-updates】react
目录:git
另:最近本瓜在参加 【掘金 2020 人气创做者榜单打榜活动】,赶快来为我 ——【掘金安东尼】投票吧!!!支持创做者!!!支持掘金!!!掘掘掘!!!github
你的点赞投票是我最大的动力,关注走一波,【2021】有更多好看~!😀😀😀web
在 Vue2 中,咱们在 main.js 一般这样进行初始化挂载:vue-router
new Vue({
render: h => h(App),
components: { App }
}).$mount('#app')
复制代码
在 Vue3 中,调整为这样:api
import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App)
app.mount('#app')
复制代码
为何发生这样的变化?缘由是:若是咱们在 Vue2 中建立多个 Vue 实例,那么全部应用(#app)都会共享全局相同的配置。数组
// 全局共享、相互影响
Vue.mixin({
/* ... */
})
Vue.directive('...', {
...
})
const app1 = new Vue({ el: '#app-1' })
const app2 = new Vue({ el: '#app-2' })
复制代码
显然,这并非咱们想要的。在 Vue3 中,你能够建立多个实例,且每一个实例均可以拥有单独的配置。markdown
import { createApp } from 'vue'
import App1 from './App1.vue'
import App2 from './App2.vue'
const app1 = createApp(App1)
const app2 = createApp(App2)
app1.mount('#app-1')
app2.mount('#app-2')
app1.directive('...', {
...
})
app2.directive('...', {
...
})
复制代码
可是,这也并不影响咱们设置共享全局配置,咱们能够经过以下工厂函数方式实现:
import { createApp } from 'vue';
import App1 from './App1.vue';
import App2 from './App2.vue';
const createApp = (Instance) => {
const App = createApp(Instance);
App.directive('i-am-cool', {
inserted: () => {
console.log('I am cool!');
},
});
}
createIdolApp(App1).mount('#app-1');
createIdolApp(App2).mount('#app-2');
复制代码
受到 React 的启发,Vue3 引入 Composition API 和 “hook” 函数。有了它,Vue 组件的使用变得更加灵活,也变得更增强大。特别是针对大型应用,如下会给出示例。
之前在 Vue2 中咱们是这样写组件的:获取数据,设置数据。
<script>
import { fetchResources } from '@/actions'
import ResourceDetail from '@/components/ResourceDetail'
import ResourceList from '@/components/ResourceList'
export default {
components: {
ResourceDetail,
ResourceList,
},
data() {
return {
title: 'Your resources',
selectedResource: null,
resources: []
}
},
async created() {
this.resources = await fetchResources()
},
computed: {
hasResources() {
return this.resourceCount > 0
},
activeResource() {
return this.selectedResource || (this.hasResources && this.resources[0]) || null
},
resourceCount(){
return this.resources.length
}
},
methods: {
selectResource(resource) {
this.selectedResource = {...resource}
}
}
}
</script>
复制代码
完整代码在这里。
若是咱们使用 composition API,会是这样写:
import { ref, onMounted, computed } from 'vue'
import { fetchResources } from '@/actions'
export default function useResources() {
const resources = ref([])
const getResources = async () => resources.value = await fetchResources()
onMounted(getResources);
const resourceCount = computed(() => resources.value.length)
const hasResources = computed(() => resourceCount.value > 0 )
return {
resources,
resourceCount,
hasResources
}
}
复制代码
这是一个很是简单的 Composition function 实现了获取 resources 数据的功能。
Composition 函数一般用 use 开头做为关键字,好比此处的 “useResources”,以此区别于普通函数。
下面针对以上代码关键点进行一一释义:
1. ref 会建立一个动态对象。若是你要从 ref 获取原始值,则须要取 “value” 属性,好比 —— resources.value
看如下示例:
var a = 7;
var b = a;
b = 10;
// a = 7
// b = 10
var a = ref(7);
var b = a;
b.value = 100;
// a = 100
// b = 100
复制代码
咱们将返回的 resoure 数组设置为 ref。是由于若是数组有新增项或移除项,这样作能在程序中有所表现。
一图胜万言:
2. getResources 函数用于获取数据。
3. onMounted 生命周期函数会在组件添加到 Dom 时调用。
4. computed 属性会随着它的依赖(resources or resourceCount)变化而从新计算。
5. return 最后一步咱们将返回 data/function,咱们再向组件暴露 useResource hook 函数以供使用。
最终 hook-in:
<script>
import ResourceDetail from '@/components/ResourceDetail'
import ResourceList from '@/components/ResourceList'
import useResources from '@/composition/useResources';
export default {
components: {
ResourceDetail,
ResourceList,
},
data() {
return {
title: 'Your resources',
selectedResource: null
}
},
setup() {
return {
...useResources() // 在 setup 里
}
},
computed: {
activeResource() {
return this.selectedResource || (this.hasResources && this.resources[0]) || null
}
},
methods: {
selectResource(resource) {
this.selectedResource = {...resource}
}
}
}
</script>
复制代码
咱们再 setup 中进行引用,返回值均可以再经过 this 进行调用。
咱们在 computed 和 methods 也能一样进行调用 Composition 函数的返回。
注意:setup 钩子函数执行在组件实例建立(created)以前。
在组件建立前 setup 中 hook 被执行,只要 props 被解析,服务就会以 composition API 做为入口。由于此时当 setup 执行时,组件实例还未生成,没有 this 对象。
神奇吗?咱们就这样将获取数据进行封装而后应用到了 hook 调用中。
再写一个对 resources 资源进行搜索过滤的功能:
import { ref, computed } from 'vue'
export default function useSearchResource(resources) {
const searchQuery = ref('')
const setSearchQuery = searched => {
searchQuery.value = searched
}
const searchedResources = computed(() => {
if (!searchQuery.value) {
return resources.value
}
const lcSearch = searchQuery.value.toLocaleLowerCase();
return resources.value.filter(r => {
const title = r?.title.toLocaleLowerCase()
return title.includes(lcSearch)
})
})
return {
setSearchQuery,
searchedResources
}
}
复制代码
export default function useResources() {
const resources = ref([])
const getResources = async () => resources.value = await fetchResources()
onMounted(getResources);
const resourceCount = computed(() => resources.value.length)
const hasResources = computed(() => resourceCount.value > 0 )
const { searchedResources, setSearchQuery } = useSearchResources(resources)
return {
resources: searchedResources,
resourceCount,
hasResources,
setSearchQuery
}
}
复制代码
拆解分析:
再看下在组件中使用它到底有多简单:
<template>
...
<input
@keyup="handleSearch"
type="text"
class="form-control"
placeholder="Some title" />
...
</template>
<script>
...
methods: {
...
handleSearch(e) {
this.setSearchQuery(e.target.value)
}
}
...
</script>
复制代码
真有你的! 不管什么时候执行 setSearchQuery 更改 searchQuery 的值,都将从新执行 searchedResources 将其进行过滤操做并返回结果。
以上即是超重要的新特性 composition API 的实战介绍。
在 Vue2 中,data选项不是对象就函数,可是在 Vue3 中将只能是函数。这将被统一成标准。
<script>
export default {
data() {
return {
someData: '1234'
}
}
}
</script>
复制代码
不会再出现这样的写法:
<h1>{{title | capitalized }} </h1>
复制代码
这样的表达式不是合法有效的 Javascript,在 Vue 中实现这样的写法须要额外的成本。它能够很容易被转化为计算属性或函数。
computed: {
capitalizedTitle() {
return title[0].toUpperCase + title.slice(1);
}
}
复制代码
在 Vue2 中咱们常常这样包裹咱们的根标签:
<template>
<div>
<h1>...</h1>
<div class="container">...</div>
...
</div>
</template>
复制代码
在 Vue3 中将再也不有此限制:
<template>
<h1>...</h1>
<div class="container">...</div>
...
</template>
复制代码
Suspense 是一种特殊的 Vue 组件,用于解析有异步数据的组件。
好比:
<Suspense>
<template #default>
<AsyncComponent>
</template>
<template #fallback>
Loading Data...
</template>
</Suspense>
复制代码
使用新的 Composition API,setup 可设置异步函数。Suspense 能够展现异步的模板直到 setup 被解析完。
实战代码:
<template>
Welcome, {{user.name}}
</template>
<script>
import { fetchUser } from '@/actions';
export default {
async setup() {
const user = await fetchUser();
return { user }
}
}
</script>
复制代码
<Suspense>
<template #default>
<UserPanel/>
</template>
<template #fallback>
Loading user ...
</template>
</Suspense>
复制代码
妇孺皆知,Vue3 的响应式也有很大变化(proxy),再也不须要使用 Vue.set 或 Vue.delete。你可使用简单的原生函数来操做数组或对象。
// in composition API
const resources = ref([])
const addResource = newResource => resources.value.unshift(newResource)
const removeResource = atIndex => resources.value.splice(atIndex ,1)
const reactiveUser = ref({name: 'Filip'})
const changeName = () => reactiveUser.value.name = 'John'
复制代码
之前则是须要这样:
<script>
export default {
data() {
return {
resources: [1,2,3],
person: { name: 'Filip' }
}
}
methods: {
addResource(newResource) {
this.resources.unshift(newResource)
},
removeResource(atIndex) {
this.resources.splice(atIndex ,1)
},
changeName(newResource) {
this.person.name = 'John'
}
}
}
</script>
复制代码
在 composition API 中,全部的更改都是响应式的。
在 Vue3 中,你可使用多个 v-model,好比这样:
<ChildComponent v-model:prop1="prop1" v-model:prop2="prop2"/>
复制代码
能够实现如下代码逻辑:
<ChildComponent
:prop1="prop1"
@update:prop1="prop1 = $event"
:prop2="prop2"
@update:prop2="prop2 = $event"
/>
复制代码
看一个具体的例子:
<resource-form
v-model:title="title"
v-model:description="description"
v-model:type="type"
v-model:link="link"
@on-form-submit="submitForm"
/>
复制代码
form 组件是这样:
<template>
<form>
<div class="mb-3">
<label htmlFor="title">Title</label>
<input
:value="title"
@input="changeTitle($event.target.value)"
type="text" />
</div>
<div class="mb-3">
<select
:value="type"
@change="changeType($event.target.value)">
<option
v-for="type in types"
:key="type"
:value="type">{{type}}</option>
</select>
</div>
<button
@click="submitForm"
class="btn btn-primary btn-lg btn-block"
type="button">
Submit
</button>
</form>
</template>
export default {
props: {
title: String,
description: String,
link: String,
type: String,
},
data() {
return {
types: ['blog', 'book', 'video']
}
},
methods: {
submitForm() {
this.$emit('on-form-submit');
},
changeTitle(title) {
this.$emit('update:title', title)
},
changeType(type) {
this.$emit('update:type', type)
}
...
}
}
复制代码
咱们绑定多个 input 值,监听变化,再emit 来更新值父组件的值。注意这里写法的格式。
提供如何在当前上下文以外只呈现模板的一部分的方法。
要“teleport”内容,咱们须要使用 teleport 组件并把内容包在里面,以下:
<teleport to="#teleportContent">
<div class="teleport-body">I am Teleported!</div>
</teleport>
复制代码
此内容将被传送到 id 为 teleportContent 的节点中
<div id="teleportContent"></div>
复制代码
惟一的条件是:在定义传送内容以前,传送到的目标节点需已经存在。
咱们能够绑定 id,类,[data-xx]。
<!-- ok -->
<teleport to="#some-id" />
<teleport to=".some-class" />
<teleport to="[data-teleport]" />
<!-- Wrong -->
<teleport to="h1" />
<teleport to="some-string" />
复制代码
Vue2 中咱们这样设置及绑定路由:
import Vue from 'vue'
import VueRouter from 'vue-router';
import SomePage1 from './pages/SomePage1';
import SomePage2 from './pages/SomePage2';
Vue.use(VueRouter);
const routes = [
{ path: '/', redirect: '/path' },
{ path: '/path', name: 'HomePage', component: SomePage1 },
{ path: '/some/path', component: SomePage2 }
]
const router = new VueRouter({
mode: 'history',
linkExactActiveClass: 'active',
routes
})
export default router;
复制代码
main.js
import router from './router';
new Vue({render: h => h(App),
router,
components: { App }})
.$mount('#app')
复制代码
在 Vue3 中:
import { createRouter, createWebHistory } from 'vue-router'
import SomePage1 from './pages/SomePage1'
import SomePage2 from './pages/SomePage2'
const routes = [
{ path: '/', redirect: {name: 'HomePage'}},
{ path: '/path', name: 'HomePage', component: SomePage1 },
{ path: '/some/path', component: SomePage2 }
]
const router = createRouter({
history: createWebHistory(),
linkExactActiveClass: 'active',
routes
})
export default router;
复制代码
main.js
import router from './router'
const app = createApp(App)
app.use(router)
app.mount('#app')
复制代码
此篇总结了 Vue3 的一些主要功能,都是从实战出发来突破 Vue3 的新特性。实践是检验真理的惟一标准!Vue3 究竟强不强?有多强?市场和时间会告诉咱们答案!从现阶段看,早学早享受QAQ~若是想要了解更多,请查阅 官方文档。
我是掘金安东尼,持续输出ING......点赞👍 + 收藏📕 + 关注👀,咱们下期再会~