当前位置:首页 > 技术分析 > 正文内容

10个实例小练习,快速入门熟练 Vue3 核心新特性(一)

ruisui884个月前 (01-07)技术分析24


作者: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移动端框架「实践」

2020前端就业Vue框架篇「实践」

详解Vue3中 router 带来了哪些变化?

Vue项目部署及性能优化指导篇「实践」

Vue高性能渲染大数据Tree组件「实践」

尤大大细品VuePress搭建技术网站与个人博客「实践」

10个Vue开发技巧「实践」

是什么导致尤大大选择放弃Webpack?【vite 原理解析】

带你了解 vue-next(Vue 3.0)之 小试牛刀【实践】

带你了解 vue-next(Vue 3.0)之 初入茅庐【实践】

实践Vue 3.0做JSX(TSX)风格的组件开发

一篇文章教你并列比较React.js和Vue.js的语法【实践】

手拉手带你开启Vue3世界的鬼斧神工【实践】

深入浅出通过vue-cli3构建一个SSR应用程序【实践】

怎样为你的 Vue.js 单页应用提速

聊聊昨晚尤雨溪现场针对Vue3.0 Beta版本新特性知识点汇总

【新消息】Vue 3.0 Beta 版本发布,你还学的动么?

Vue真是太好了 壹万多字的Vue知识点 超详细!

Vue + Koa从零打造一个H5页面可视化编辑器——Quark-h5

深入浅出Vue3 跟着尤雨溪学 TypeScript 之 Ref 【实践】

手把手教你深入浅出vue-cli3升级vue-cli4的方法

Vue 3.0 Beta 和React 开发者分别杠上了

手把手教你用vue drag chart 实现一个可以拖动 / 缩放的图表组件

Vue3 尝鲜

总结Vue组件的通信

手把手让你成为更好的Vue.js开发人员的12个技巧和窍门【实践】

Vue 开源项目 TOP45

2020 年,Vue 受欢迎程度是否会超过 React?

尤雨溪:Vue 3.0的设计原则

使用vue实现HTML页面生成图片

实现全栈收银系统(Node+Vue)(上)

实现全栈收银系统(Node+Vue)(下)

vue引入原生高德地图

Vue合理配置WebSocket并实现群聊

多年vue项目实战经验汇总

vue之将echart封装为组件

基于 Vue 的两层吸顶踩坑总结

Vue插件总结【前端开发必备】

Vue 开发必须知道的 36 个技巧【近1W字】

构建大型 Vue.js 项目的10条建议

深入理解vue中的slot与slot-scope

手把手教你Vue解析pdf(base64)转图片【实践】

使用vue+node搭建前端异常监控系统

推荐 8 个漂亮的 vue.js 进度条组件

基于Vue实现拖拽升级(九宫格拖拽)

手摸手,带你用vue撸后台 系列二(登录权限篇)

手摸手,带你用vue撸后台 系列三(实战篇)

前端框架用vue还是react?清晰对比两者差异

Vue组件间通信几种方式,你用哪种?【实践】

浅析 React / Vue 跨端渲染原理与实现

10个Vue开发技巧助力成为更好的工程师

手把手教你Vue之父子组件间通信实践讲解【props、$ref 、$emit】

1W字长文+多图,带你了解vue的双向数据绑定源码实现

深入浅出Vue3 的响应式和以前的区别到底在哪里?【实践】

干货满满!如何优雅简洁地实现时钟翻牌器(支持JS/Vue/React)

基于Vue/VueRouter/Vuex/Axios登录路由和接口级拦截原理与实现

手把手教你D3.js 实现数据可视化极速上手到Vue应用

吃透 Vue 项目开发实践|16个方面深入前端工程化开发技巧【上】

吃透 Vue 项目开发实践|16个方面深入前端工程化开发技巧【中】

吃透 Vue 项目开发实践|16个方面深入前端工程化开发技巧【下】

Vue3.0权限管理实现流程【实践】

后台管理系统,前端Vue根据角色动态设置菜单栏和路由

作者:xuying 全栈修炼

转发链接:https://mp.weixin.qq.com/s/_n2seDbbiO5hXQfuUGbUCQ

扫描二维码推送至手机访问。

版权声明:本文由ruisui88发布,如需转载请注明出处。

本文链接:http://www.ruisui88.com/post/97.html

分享给朋友:

“10个实例小练习,快速入门熟练 Vue3 核心新特性(一)” 的相关文章

gitlab 分支保护设置

一、功能描述代码管理中管理,我们把稳定的分支设置为保护,可以防止其他人员误操作(例如删除,合并,推送代码等)。二、Gitlab配置步骤1 点击项目Repository标签2.点击Expand标签3.配置如下:默认master是被保护的,而且只有维护人员具有推送和合并权限。设置保护分支,这里的beta...

学无止境:Git 如何优雅地回退代码

来源:https://zhenbianshu.github.io前言从接触编程就开始使用 Git 进行代码管理,先是自己玩 Github,又在工作中使用 Gitlab,虽然使用时间挺长,可是也只进行一些常用操作,如推拉代码、提交、合并等,更复杂的操作没有使用过,看过的教程也逐渐淡忘了,有些对不起 L...

身体越柔软越好?刻苦拉伸可能反而不健康 | 果断练

坐下伸直膝盖,双手用力向前伸,再用力……比昨天前进了一厘米,又进步了! 这么努力地拉伸,每个人都有自己的目标,也许是身体健康、线条柔美、放松肌肉、体测满分,也可能为了随时劈个叉,享受一片惊呼。 不过,身体柔软,可以享受到灵活的福利,也可能付出不稳定的代价,并不是越刻苦拉伸越好。太硬或者太软,都不安全...

美国民众负债累累 但今年假期消费者支出仍将创下新高

智通财经APP获悉,在迎接假期之际,许多美国人已经背负了创纪录的信用卡债务。然而,今年假期消费者支出仍将创下新高。根据美国零售联合会(NRF)上周发布的报告,预计今年11月1日至12月31日期间的消费总额将达到创纪录的9795亿至9890亿美元之间。NRF首席经济学家Jack Kleinhenz表示...

深入理解vue-router原理

说到vue-router就表明他只适合于vue和vue是强绑定的关系;不适合其他框架;现在我们模仿实现一个VueRouter;1.要使页面刷新;借助vue本身的响应式原理;import Home from "./views/Home"; import About from "...

SpringBoot2.X+Vue+UniAPP,全栈开发医疗小程序

//xia仔のke:chaoxingit.com/208/全栈开发医疗小程序:利用Spring Boot 2.X、Vue和UniApp在当今数字化时代,医疗行业也在不断地迈向信息化和智能化的方向。开发一款医疗小程序,能够为用户提供便捷的医疗服务和信息查询,为医疗机构提供高效的管理和服务渠道。本文将介...