10个实例小练习,快速入门熟练 Vue3 核心新特性(一)
ztj100 2024-12-29 07:21 29 浏览 0 评论
作者:xuying 全栈修炼
转发链接:https://mp.weixin.qq.com/s/_n2seDbbiO5hXQfuUGbUCQ
前言
Vue3.0 发 beta 版都有一段时间了,正式版也不远了,所以真的要学习一下 Vue3.0 的语法了。本篇文章总共分两部分,望小伙伴们认真阅读。
下一篇:10个实例小练习,快速入门熟练 Vue3 核心新特性(二)
环境搭建
$ git pull https://github.com/vuejs/vue-next.git
$ cd vue-next && yarn
下载完成之后打开代码, 开启 sourceMap :
- tsconfig.json 把 sourceMap 字段修改为 true: "sourceMap": true
- rollup.config.js 在 rollup.config.js 中,手动键入:output.sourcemap = true
- 生成 vue 全局的文件:yarn dev
- 在根目录创建一个 demo 目录用于存放示例代码,并在 demo 目录下创建 html 文件,引入构建后的 vue 文件
api 的使用都是很简单的,下文的内容,看例子代码就能懂了的,所以下面的例子不会做过多解释。
reactive
reactive: 创建响应式数据对象
setup 函数是个新的入口函数,相当于 vue2.x 中 beforeCreate 和 created,在 beforeCreate 之后 created 之前执行。
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Hello Vue3.0</title>
<style> body,
#app {
text-align: center;
padding: 30px;
}
</style>
<script src="../../packages/vue/dist/vue.global.js"></script>
</head>
<body>
<h3>reactive</h3>
<div id='app'></div>
</body>
<script> const { createApp, reactive } = Vue
const App = {
template: `
<button @click='click'>reverse</button>
<div style="margin-top: 20px">{{ state.message }}</div>
`,
setup() {
console.log('setup ');
const state = reactive({
message: 'Hello Vue3!!'
})
click = () => {
state.message = state.message.split('').reverse().join('')
}
return {
state,
click
}
}
}
createApp(App).mount('#app')</script>
</html>
ref & isRef
ref : 创建一个响应式的数据对象 isRef : 检查值是否是 ref 的引用对象。
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Hello Vue3.0</title>
<style> body,
#app {
text-align: center;
padding: 30px;
}
</style>
<script src="../../packages/vue/dist/vue.global.js"></script>
</head>
<body>
<h3>ref & isRef</h3>
<div id='app'></div>
</body>
<script> const { createApp, reactive, ref, isRef } = Vue
const App = {
template: `
<button @click='click'>count++</button>
<div style="margin-top: 20px">{{ count }}</div>
`,
setup() {
const count = ref(0);
console.log("count.value:", count.value) // 0
count.value++
console.log("count.value:", count.value) // 1
// 判断某值是否是响应式类型
console.log('count is ref:', isRef(count))
click = () => {
count.value++;
console.log("click count.value:", count.value)
}
return {
count,
click,
}
}
}
createApp(App).mount('#app')</script>
</html>
Template Refs
使用 Composition API 时,反应性引用和模板引用的概念是统一的。
为了获得对模板中元素或组件实例的引用,我们可以像往常一样声明 ref 并从 setup() 返回。
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Hello Vue3.0</title>
<style> body,
#app {
text-align: center;
padding: 30px;
}
</style>
<script src="../../packages/vue/dist/vue.global.js"></script>
</head>
<body>
<h3>Template Refs</h3>
<div id='app'></div>
</body>
<script> const { createApp, reactive, ref, isRef, toRefs, onMounted, onBeforeUpdate } = Vue
const App = {
template: `
<button @click='click'>count++</button>
<div ref="count" style="margin-top: 20px">{{ count }}</div>
`,
setup() {
const count = ref(null);
onMounted(() => {
// the DOM element will be assigned to the ref after initial render
console.log(count.value) // <div/>
})
click = () => {
count.value++;
console.log("click count.value:", count.value)
}
return {
count,
click
}
}
}
createApp(App).mount('#app')</script>
</html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Hello Vue3.0</title>
<style> body,
#app {
text-align: center;
padding: 30px;
}
</style>
<script src="../../packages/vue/dist/vue.global.js"></script>
</head>
<body>
<h3>Template Refs</h3>
<div id='app'></div>
</body>
<script> const { createApp, reactive, ref, isRef, toRefs, onMounted, onBeforeUpdate } = Vue
const App = {
template: `
<div v-for="(item, i) in list" :ref="el => { divs[i] = el }">
{{ item }}
</div>
`,
setup() {
const list = reactive([1, 2, 3])
const divs = ref([])
// make sure to reset the refs before each update
onBeforeUpdate(() => {
divs.value = []
})
onMounted(() => {
// the DOM element will be assigned to the ref after initial render
console.log(divs.value) // [<div/>]
})
return {
list,
divs
}
}
}
createApp(App).mount('#app')</script>
</html>
toRefs
toRefs : 将响应式数据对象转换为单一响应式对象
将一个 reactive 代理对象打平,转换为 ref 代理对象,使得对象的属性可以直接在 template 上使用。
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Hello Vue3.0</title>
<style> body,
#app {
text-align: center;
padding: 30px;
}
</style>
<script src="../../packages/vue/dist/vue.global.js"></script>
</head>
<body>
<h3>toRefs</h3>
<div id='app'></div>
</body>
<script> const { createApp, reactive, ref, isRef, toRefs } = Vue
const App = {
// template: `
// <button @click='click'>reverse</button>
// <div style="margin-top: 20px">{{ state.message }}</div>
// `,
// setup() {
// const state = reactive({
// message: 'Hello Vue3.0!!'
// })
// click = () => {
// state.message = state.message.split('').reverse().join('')
// console.log('state.message: ', state.message)
// }
// return {
// state,
// click
// }
// }
template: `
<button @click='click'>count++</button>
<div style="margin-top: 20px">{{ message }}</div>
`,
setup() {
const state = reactive({
message: 'Hello Vue3.0!!'
})
click = () => {
state.message = state.message.split('').reverse().join('')
console.log('state.message: ', state.message)
}
return {
click,
...toRefs(state)
}
}
}
createApp(App).mount('#app')</script>
</html>
computed
computed : 创建计算属性
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Hello Vue3.0</title>
<style> body,
#app {
text-align: center;
padding: 30px;
}
</style>
<script src="../../packages/vue/dist/vue.global.js"></script>
</head>
<body>
<h3>computed</h3>
<div id='app'></div>
</body>
<script> const { createApp, reactive, ref, computed } = Vue
const App = {
template: `
<button @click='handleClick'>count++</button>
<div style="margin-top: 20px">{{ count }}</div>
`,
setup() {
const refData = ref(0);
const count = computed(()=>{
return refData.value;
})
const handleClick = () =>{
refData.value += 1 // 要修改 count 的依赖项 refData
}
console.log("refData:" , refData)
return {
count,
handleClick
}
}
}
createApp(App).mount('#app')</script>
</html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Hello Vue3.0</title>
<style> body,
#app {
text-align: center;
padding: 30px;
}
</style>
<script src="../../packages/vue/dist/vue.global.js"></script>
</head>
<body>
<h3>computed</h3>
<div id='app'></div>
</body>
<script> const { createApp, reactive, ref, computed } = Vue
const App = {
template: `
<button @click='handleClick'>count++</button>
<div style="margin-top: 20px">{{ count }}</div>
`,
setup() {
const refData = ref(0);
const count = computed({
get(){
return refData.value;
},
set(value){
console.log("value:", value)
refData.value = value;
}
})
const handleClick = () =>{
count.value += 1 // 直接修改 count
}
console.log(refData)
return {
count,
handleClick
}
}
}
createApp(App).mount('#app')</script>
</html>
最后
本文只列出了笔者觉得会用得非常多的 api,Vue3.0 里面还有不少新特性的,比如 customRef、markRaw ,如果读者有兴趣可看 Vue Composition API 文档。
- Vue Composition API 文档: https://composition-api.vuejs.org/api.html#setup
- vue-next 地址: https://github.com/vuejs/vue-next
本篇文章未完结,请查看下一篇。
推荐Vue学习资料文章:
《10个实例小练习,快速入门熟练 Vue3 核心新特性(二)》
《10个实例小练习,快速入门熟练 Vue3 核心新特性(一)》
《教你部署搭建一个Vue-cli4+Webpack移动端框架「实践」》
《尤大大细品VuePress搭建技术网站与个人博客「实践」》
《是什么导致尤大大选择放弃Webpack?【vite 原理解析】》
《带你了解 vue-next(Vue 3.0)之 小试牛刀【实践】》
《带你了解 vue-next(Vue 3.0)之 初入茅庐【实践】》
《一篇文章教你并列比较React.js和Vue.js的语法【实践】》
《深入浅出通过vue-cli3构建一个SSR应用程序【实践】》
《聊聊昨晚尤雨溪现场针对Vue3.0 Beta版本新特性知识点汇总》
《【新消息】Vue 3.0 Beta 版本发布,你还学的动么?》
《Vue + Koa从零打造一个H5页面可视化编辑器——Quark-h5》
《深入浅出Vue3 跟着尤雨溪学 TypeScript 之 Ref 【实践】》
《手把手教你深入浅出vue-cli3升级vue-cli4的方法》
《Vue 3.0 Beta 和React 开发者分别杠上了》
《手把手教你用vue drag chart 实现一个可以拖动 / 缩放的图表组件》
《Vue3 尝鲜》
《手把手让你成为更好的Vue.js开发人员的12个技巧和窍门【实践】》
《2020 年,Vue 受欢迎程度是否会超过 React?》
《手把手教你Vue解析pdf(base64)转图片【实践】》
《手把手教你Vue之父子组件间通信实践讲解【props、$ref 、$emit】》
《深入浅出Vue3 的响应式和以前的区别到底在哪里?【实践】》
《干货满满!如何优雅简洁地实现时钟翻牌器(支持JS/Vue/React)》
《基于Vue/VueRouter/Vuex/Axios登录路由和接口级拦截原理与实现》
《手把手教你D3.js 实现数据可视化极速上手到Vue应用》
《吃透 Vue 项目开发实践|16个方面深入前端工程化开发技巧【上】》
《吃透 Vue 项目开发实践|16个方面深入前端工程化开发技巧【中】》
《吃透 Vue 项目开发实践|16个方面深入前端工程化开发技巧【下】》
作者:xuying 全栈修炼
转发链接:https://mp.weixin.qq.com/s/_n2seDbbiO5hXQfuUGbUCQ
相关推荐
-
- SpringBoot如何实现优雅的参数校验
-
平常业务中肯定少不了校验,如果我们把大量的校验代码夹杂到业务中,肯定是不优雅的,对于一些简单的校验,我们可以使用java为我们提供的api进行处理,同时对于一些...
-
2025-05-11 19:46 ztj100
- Java中的空指针怎么处理?
-
#暑期创作大赛#Java程序员工作中遇到最多的错误就是空指针异常,无论你多么细心,一不留神就从代码的某个地方冒出NullPointerException,令人头疼。...
- 一坨一坨 if/else 参数校验,被 SpringBoot 参数校验组件整干净了
-
来源:https://mp.weixin.qq.com/s/ZVOiT-_C3f-g7aj3760Q-g...
- 用了这两款插件,同事再也不说我代码写的烂了
-
同事:你的代码写的不行啊,不够规范啊。我:我写的代码怎么可能不规范,不要胡说。于是同事打开我的IDEA,安装了一个插件,然后执行了一下,规范不规范,看报告吧。这可怎么是好,这玩意竟然给我挑出来这么...
- SpringBoot中6种拦截器使用场景
-
SpringBoot中6种拦截器使用场景,下面是思维导图详细总结一、拦截器基础...
- 用注解进行参数校验,spring validation介绍、使用、实现原理分析
-
springvalidation是什么在平时的需求开发中,经常会有参数校验的需求,比如一个接收用户注册请求的接口,要校验用户传入的用户名不能为空、用户名长度不超过20个字符、传入的手机号是合法的手机...
- 快速上手:SpringBoot自定义请求参数校验
-
作者:UncleChen来源:http://unclechen.github.io/最近在工作中遇到写一些API,这些API的请求参数非常多,嵌套也非常复杂,如果参数的校验代码全部都手动去实现,写起来...
- 分布式微服务架构组件
-
1、服务发现-Nacos服务发现、配置管理、服务治理及管理,同类产品还有ZooKeeper、Eureka、Consulhttps://nacos.io/zh-cn/docs/what-is-nacos...
- 优雅的参数校验,告别冗余if-else
-
一、参数校验简介...
- Spring Boot断言深度指南:用断言机制为代码构筑健壮防线
-
在SpringBoot开发中,断言(Assert)如同代码的"体检医生",能在上线前精准捕捉业务逻辑漏洞。本文将结合企业级实践,解析如何通过断言机制实现代码自检、异常预警与性能优化三...
- 如何在项目中优雅的校验参数
-
本文看点前言验证数据是贯穿所有应用程序层(从表示层到持久层)的常见任务。通常在每一层实现相同的验证逻辑,这既费时又容易出错。为了避免重复这些验证,开发人员经常将验证逻辑直接捆绑到域模型中,将域类与验证...
- SpingBoot项目使用@Validated和@Valid参数校验
-
一、什么是参数校验?我们在后端开发中,经常遇到的一个问题就是入参校验。简单来说就是对一个方法入参的参数进行校验,看是否符合我们的要求。比如入参要求是一个金额,你前端没做限制,用户随便过来一个负数,或者...
- 28个验证注解,通过业务案例让你精通Java数据校验(收藏篇)
-
在现代软件开发中,数据验证是确保应用程序健壮性和可靠性的关键环节。JavaBeanValidation(JSR380)作为一个功能强大的规范,为我们提供了一套全面的注解工具集,这些注解能够帮...
- Springboot @NotBlank参数校验失效汇总
-
有时候明明一个微服务里的@Validated和@NotBlank用的好好的,但就是另一个里不能用,这时候问题是最不好排查的,下面列举了各种失效情况的汇总,供各位参考:1、版本问题springbo...
- 这可能是最全面的Spring面试八股文了
-
Spring是什么?Spring是一个轻量级的控制反转(IoC)和面向切面(AOP)的容器框架。...
你 发表评论:
欢迎- 一周热门
- 最近发表
- 标签列表
-
- idea eval reset (50)
- vue dispatch (70)
- update canceled (42)
- order by asc (53)
- spring gateway (67)
- 简单代码编程 贪吃蛇 (40)
- transforms.resize (33)
- redisson trylock (35)
- 卸载node (35)
- np.reshape (33)
- torch.arange (34)
- node卸载 (33)
- npm 源 (35)
- vue3 deep (35)
- win10 ssh (35)
- exceptionininitializererror (33)
- vue foreach (34)
- idea设置编码为utf8 (35)
- vue 数组添加元素 (34)
- std find (34)
- tablefield注解用途 (35)
- python str转json (34)
- java websocket客户端 (34)
- tensor.view (34)
- java jackson (34)