vue3快速笔记
-
参考地址:
https://blog.csdn.net/sq91fra/article/details/135963246 -
在
vue3中,一个vue组件必不可少的标签只有<template>,其余两个都可以省略 -
基础示例: 插值语法演示
// App.vue<script setup>
......
const message = "Hello World.vue"
</script><template><h1>这是App根组件</h1><hr /><p>生成一个随机数字:{{(Math.random()*10).toFixed(2)}}</p><div>{{message}}</div></template><style scoped>
......
</style>
- 响应式数据演示:
- 注意:以下示例中,随机数也会一起更新
<script setup>
import HelloWorld from './components/HelloWorld.vue'
import TheWelcome from './components/TheWelcome.vue'import {ref} from 'vue'const count = ref(0)
function increment () {count.value++console.log(count)
}
</script><template><h1>这是App根组件</h1><hr /><p>生成一个随机数字:{{(Math.random()*10).toFixed(2)}}</p><button @click="increment">Count值为: {{count}}</button>
</template><style scoped>
......
</style>
这是因为 Vue 的响应式更新机制 导致的。
原因分析
-
响应式依赖追踪
当你在模板中使用{{ count }}时,Vue 会建立依赖关系:模板依赖于count这个响应式变量。 -
组件重新渲染
当你点击按钮调用increment()时:count.value++修改了响应式数据- Vue 检测到响应式数据变化
- 触发整个组件的重新渲染(Template会重新更新,故表达式会被重新计算)
-
模板重新执行
在重新渲染过程中,模板中的所有表达式都会重新计算,包括:<p>生成一个随机数字:{{(Math.random()*10).toFixed(2)}}</p>所以每次点击按钮,随机数都会重新生成。
解决办法,使用computed缓存
<script setup>
......import {ref,computed} from 'vue'const count = ref(0)
const randomNumber = computed(()=>(Math.random()*10).toFixed(2))function increment () {count.value++console.log(count)
}</script><template><h1>这是App根组件</h1><hr /><p>生成一个随机数字:{{randomNumber}}</p><div><button @click="increment">Count值为: {{count}}</button></div></template><style scoped>
......
</style>
两种API
Vue3引入了许多新特性和优化,其中包括对Composition API (组合式 API)的添加,它作为新的核心特性与原有的Options API(选项式 API )一起工作
- 选项式 API 是 Vue.js 传统的组件写法,适合简单的组件和初学者。选项式 API 的优点是结构清晰,易于理解和上手。但是,当组件变得复杂时,相关的逻辑会分散在不同的选项中,使得代码组织和重用变得困难。- 组合式 API 是 Vue 3 引入的新特性,提供了更灵活的代码组织和重用方式,可以更容易地将相关的逻辑组合在一起,并且可以跨组件重用这些逻辑。这对于编写大型和复杂的组件尤其有用。- 开发者可以根据自己的需求选择使用 Options API 或 Composition API,两者可以共存于同一个组件中。这使得开发者可以渐进式地升级现有项目到 Vue 3,同时享受 Composition API 带来的灵活性。
setup函数介绍(和vue2中的data写法类似)
- 使用了Vue 3的Composition API,但是以选项式API的写法在``标签中使用了
setup函数举例
<script>import {reactive} from "vue";export default {setup(){ // Composition API的入口,在组件创建前执行let msg = "Hello"; // 普通变量 - 非响应式let stu = reactive({ // 声明响应式对象name:'cxk',age:18,gender:'女',hobby:{hobby1:'唱',hobby2:'跳',hobby3:'Rap',hobby4:'篮球',}});return { // 最后返回模板需要的数据msg,stu}}
}</script><template><h1>{{msg}}</h1><hr><h2>大家好,我是{{stu.name}},喜欢{{stu.hobby.hobby1}},{{stu.hobby.hobby2}},{{stu.hobby.hobby3}},{{stu.hobby.hobby4}}</h2></template><style scoped>
......
</style>
setup函数这种写法,和vue2中的data写法很类似
// Vue 2 写法
export default {data() {......return {msg: "Hello",stu: {name: 'cxk',// ...}}}
}// Vue 3 写法
export default {setup() {let msg = "Hello";let stu = reactive({name: 'cxk',// ...});return { msg, stu };}
}