通过10个实例小练习,快速入门熟练 Vue3.0 核心新特性(下)

简介: 通过10个实例小练习,快速入门熟练 Vue3.0 核心新特性

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>


微信图片_20220512184534.gif


<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>


微信图片_20220512194706.gif


watch & watchEffect


watch : 创建 watch 监听

watchEffect : 如果响应性的属性有变更,就会触发这个函数


<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>watch && watchEffect</h3>
    <div id='app'></div>
</body>
<script>
    const { createApp, reactive, ref, watch, watchEffect } = Vue
    const App = {
        template: `
            <div class="container">
                <button style="margin-left: 10px" @click="handleClick()">按钮</button>
                <button style="margin-left: 10px" @click="handleStop">停止 watch</button>
                <button style="margin-left: 10px" @click="handleStopWatchEffect">停止 watchEffect</button>
                <div style="margin-top: 20px">{{ refData }}</div>
            </div>`
        ,
        setup() {
            let refData = ref(0);
            const handleClick = () =>{
                refData.value += 1
            }
            const stop = watch(refData, (val, oldVal) => {
                console.log('watch ', refData.value)
            })
            const stopWatchEffect = watchEffect(() => {
                console.log('watchEffect ', refData.value)
            })
            const handleStop = () =>{
                stop()
            }
            const handleStopWatchEffect = () =>{
                stopWatchEffect()
            }
            return {
                refData, 
                handleClick,
                handleStop,
                handleStopWatchEffect
            }
        }
    }
    createApp(App).mount('#app')
</script>
</html>


微信图片_20220512194838.gif


v-model


v-model:就是双向绑定

<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>v-model</h3>
    <div id='app'></div>
</body>
<script>
    const { createApp, reactive, watchEffect } = Vue
    const App = {
        template: `<button @click='click'>reverse</button> 
                    <div></div>
                    <input v-model="state.message" style="margin-top: 20px" />
                    <div style="margin-top: 20px">{{ state.message }}</div>`,
        setup() {
            const state = reactive({
                message:'Hello Vue 3!!'
            })
            watchEffect(() => {
                console.log('state change ', state.message)
            })
            click = () => {
                state.message = state.message.split('').reverse().join('')
            }
            return {
                state,
                click
            }
        }
    }
    createApp(App).mount('#app')
</script>
</html>


微信图片_20220512194911.gif


readonly


使用 readonly 函数,可以把 普通 object 对象reactive 对象ref 对象 返回一个只读对象。


返回的 readonly 对象,一旦修改就会在 consolewarning 警告。

程序还是会照常运行,不会报错。


<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>readonly</h3>
    <div id='app'></div>
</body>
<script>
    const { createApp, reactive, readonly, watchEffect } = Vue
    const App = {
        template: `
            <button @click='click'>reverse</button> 
            <button @click='clickReadonly' style="margin-left: 20px">readonly++</button> 
            <div style="margin-top: 20px">{{ original.count }}</div>
        `,
        setup() {
            const original = reactive({ count: 0 })
            const copy = readonly(original)
            watchEffect(() => {
                // works for reactivity tracking
                console.log(copy.count)
            })
            click = () => {
                // mutating original will trigger watchers relying on the copy
                original.count++
            }
            clickReadonly = () => {
                // mutating the copy will fail and result in a warning
                copy.count++ // warning!
            }
            return {
                original,
                click,
                clickReadonly
            }
        }
    }
    createApp(App).mount('#app')
</script>
</html>


微信图片_20220512195001.gif


provide & inject


provideinject 启用类似于 2.x provide / inject 选项的依赖项注入。


两者都只能在 setup() 当前活动实例期间调用。


import { provide, inject } from 'vue'
const ThemeSymbol = Symbol()
const Ancestor = {
  setup() {
    provide(ThemeSymbol, 'dark')
  }
}
const Descendent = {
  setup() {
    const theme = inject(ThemeSymbol, 'light' /* optional default value */)
    return {
      theme
    }
  }
}


inject 接受可选的默认值作为第二个参数。


如果未提供默认值,并且在 Provide 上下文中找不到该属性,则 inject 返回 undefined


Lifecycle Hooks


Vue2 与 Vue3 的生命周期勾子对比:

| Vue2 | Vue3 |

| :------ | :------ |

| beforeCreate | setup(替代) |

| created | setup(替代) |

| beforeMount | onBeforeMount |

| mounted | onMounted |

| beforeUpdate | onBeforeUpdate |

| updated | onUpdated |

| beforeDestroy | onBeforeUnmount |

| destroyed | onUnmounted |

| errorCaptured | onErrorCaptured |

| 空 | onRenderTracked |

| 空 | onRenderTriggered |

除了 2.x 生命周期等效项之外,Composition API 还提供了以下调试挂钩:


  • onRenderTracked
  • onRenderTriggered


这两个钩子都收到一个 DebuggerEvent,类似于观察者的 onTrackonTrigger 选项:


export default {
  onRenderTriggered(e) {
    debugger
    // inspect which dependency is causing the component to re-render
  }
}



例子:


<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>Lifecycle Hooks</h3>
    <div id='app'></div>
</body>
<script>
    const { createApp, reactive, onMounted, onUpdated, onUnmounted } = Vue
    const App = {
        template: `
            <div class="container">
                <button @click='click'>reverse</button>
                <div style="margin-top: 20px">{{ state.message }}</div>
            </div>`
        ,
        setup() {
            console.log('setup!')
            const state = reactive({
                message: 'Hello Vue3!!'
            })
            click = () => {
                state.message = state.message.split('').reverse().join('')
            }
            onMounted(() => {
                console.log('mounted!')
            })
            onUpdated(() => {
                console.log('updated!')
            })
            onUnmounted(() => {
                console.log('unmounted!')
            })
            return {
                state,
                click
            }
        }
    }
    createApp(App).mount('#app')
</script>
</html>


微信图片_20220512195130.gif

相关文章
|
3月前
|
JavaScript 前端开发 开发者
Vue第1天:特性概览
Vue第1天:特性概览
|
3月前
|
缓存 JavaScript
Vue3 的模板语法:指令、插值语法和其他相关特性
Vue3 的模板语法:指令、插值语法和其他相关特性
159 4
Vue3 的模板语法:指令、插值语法和其他相关特性
|
3月前
|
JavaScript 算法 编译器
Vue3的新特性
Vue3的新特性
139 0
|
5天前
|
JavaScript 算法 API
Vue 3有哪些新特性
【8月更文挑战第16天】Vue 3有哪些新特性
29 1
|
12天前
|
JavaScript 前端开发 搜索推荐
揭秘 Vue 3 的 Teleport 特性,让你实现跨组件传输内容,使得开发变得更加得心应手!!
揭秘 Vue 3 的 Teleport 特性,让你实现跨组件传输内容,使得开发变得更加得心应手!!
|
2月前
|
缓存 JavaScript 前端开发
vue的一些特性
vue的一些特性
20 0
|
3月前
|
开发框架 JavaScript 算法
了解vue3的基本特性和底层原理
Vue3的底层原理涵盖了响应式系统的Proxy-based实现、组件的模板编译与渲染更新机制、组合式API带来的逻辑组织变革,以及其他关键特性的具体实现。这些原理共同构成了Vue3强大、高效、灵活的现代前端开发框架基础。
243 2
|
3月前
|
JavaScript 前端开发 编译器
Vue 3:新特性与改进技术详解
【4月更文挑战第25天】Vue 3 提升了编译和运行时性能,引入了Composition API实现灵活代码复用,新增Teleport用于任意位置渲染,支持Fragment多根节点及Suspense处理异步组件。同时,TypeScript支持增强,自定义指令和全局API也得到优化。Vue 3的新特性旨在提供更高效、灵活的开发体验,持续引领前端技术发展。
|
9月前
|
JavaScript 前端开发 编译器
你知道Vue 3.0中Treeshaking特性吗?
你知道Vue 3.0中Treeshaking特性吗?
174 0
|
3月前
|
JavaScript 前端开发 API
Vue3有哪些新特性
【4月更文挑战第15天】 Vue3带来了显著性能提升和开发体验优化:更快的渲染速度、更小的捆绑体积、改进的内存管理、增强的TypeScript支持、引入Composition API提升代码复用性,以及使用Proxy改进响应式数据处理。这些特性使Vue3成为更高效、灵活和可靠的框架,为开发者创造高性能应用提供了强大工具。
29 0