前言:距vue3.2发布已一年有余,3.2新增的setup的语法糖写法 作为紧跟时代的前端开发者是必须要会的,多一项技能也就多一项能在时代洪流中争渡的本钱,本文主要是介绍一些vue3.2日常中用到的比较多的写法,也当给自己几个月来的学习做一个总结归纳...
页面结构
<template>
<div></div>
// ...
</template>
<script setup>
const color = ref('red')
// ...
</script>
<style lang="scss" scoped>
div {
color:v-bind(color)
}
// ...
</style>
页面结构上没有太多变化,要注意的是1、<script setup>
是一种编译时语法糖,能够极大改善在 SFC (单页面组件)中使用 Composition API 时的开发者体验。
2、<style> v-bind
用于在 SFC <style>
标签中启用组件状态驱动的动态 CSS 值。
声明变量
<script setup>
import { reactive,ref } from 'vue'
// ref
const num = ref(500);
const str = ref('qwert');
const bol = ref(true);
const obj = ref({
cup : 'D',
height : 180
});
// reactive
const people = reactive({
age : 18,
name : 'jian'
})
// ref与reactive 修改/赋值
num.value = 600
people.age = 20
</script>
要注意的是ref声明的是响应式的区别:
1、ref 声明的是响应式的变量,而reactive 不是响应式的,只能通过赋值的方式改变
2、reactive 接收的必须是对象形式,而 ref 可以是对象形式,也可以是一个其他基础类型
3、读取/赋值不一样,ref 必须从.value 属性中读取值
4、ref存在异步问题
method方法
<template>
<div @click='clickchange()'></div>
// ...
</template>
<script setup>
const color = ref('red')
const clickchange = () => {
color.value = 'blue'
}
</script>
<style lang="scss" scoped>
div {
color:v-bind(color)
}
// ...
</style>
method 直接写成箭头函数的形式表示
watch与computed
<script setup>
import { watch, computed, ref } from 'vue'
const num = ref(0)
// 要监听的对象
const obj = ref({
cup : 'D',
height : 180
});
// 通过computed获得递增 (计算属性)
const num = computed(() => {
return count.value++
})
// 监听对象的改变 (侦听)
watch(
() => obj.cup,
(newVal, oldVal) => {
console.log(obj.cup)
console.log(`watch监听变化前的数据:${oldVal}`)
console.log(`watch监听变化后的数据:${newVal}`)
},
{
immediate: true, // 立即执行
deep: true // 深度监听
}
)
</script>
父子组件传值
父
<template>
<div>
<child :name='people.bra' @updateName='updatebra'/>
</div>
</template>
<script setup>
import { reactive } from 'vue'
// 引入子组件
import child from './child.vue'
const people = reactive({
bra: 'e'
})
// 接收子组件触发的方法
const updatebra= (bra) => {
people.bra = a
}
</script>
子
<template>
<div>
<span>{{props.bra}}</span>
<span>{{bra}}</span>
<button @click='changebra'>更名</button>
</div>
</template>
<script setup>
// import { defineEmits, defineProps } from 'vue'
// defineEmits和defineProps在<script setup>中自动可用,无需导入
// 需在.eslintrc.js文件中【globals】下配置【defineEmits: true】、【defineProps: true】
// 声明 props 属性
const props = defineProps({
bra: {
type: String,
default: ''
}
})
// 声明 emit 事件
const emit = defineEmits(['updatebra'])
const changebra = () => {
emit('updatebra', 'a')
}
</script>
待更新ing...
原创码字不易,如果你觉得对你有帮助的好劳烦你动动你的小手点个赞,当然关注收藏三连就更好了!!!^_^!