vue中setup語法糖寫法實例
變量聲明
變量聲明定義的時候,不需要返回可以直接使用即可
沒有使用setup語法糖時寫法
<script> import {useStore} from 'vuex' export default { setup() { const store=useStore() const plus=()=>{ store.commit('plus') } return {plus} }, } </script>
使用setup語法糖寫法
<script setup> import { reactive, ref, toRefs } from "vue"; let num = ref(100); const plus = ()=>{ num.value++; } let {name,age} = toRefs(reactive({ name:"張三", age:20, })); </script>
toRefs解析reactive數(shù)據(jù),可以通過解構(gòu)賦值進行數(shù)據(jù)獲取
在setup中使用toRefs來解析對象,在非setup中使用...toRefs()方法來解析,這也是一個區(qū)別
setup語法糖組件只需要導(dǎo)入,不需要注冊組件
<template> <div> {{name}}--{{age}} <el-button @click="plus">Plus</el-button> <son/> </div> </template> <script setup> import { reactive, ref, toRefs } from "vue"; import son from "../components/Son.vue" let num = ref(100); const plus = ()=>{ num.value++; } let {name,age} = toRefs(reactive({ name:"張三", age:20, })); </script>
在非setup語法糖中我們需要使用components來注冊子組件
setup語法糖中父子組件通信也發(fā)生了變化,使用defineProps和defineEmits來進行父子組件通信
父傳子
父組件
<template> <div> {{name}}--{{age}} <Son :num="age" :name='name' /> </div> </template> <script setup> import { reactive, ref, toRefs } from "vue"; import Son from "./Son.vue" let {name,age} = toRefs(reactive({ name:"張三", age:20, })); </script>
子組件
<template> <div> <h3>Son子組件--{{num}}--{{name}}</h3> </div> </template> <script setup> import { ref,defineEmits } from "vue" defineProps({ num:{ type:Number, }, name:{ type:String, } }) </script>
子傳父
父組件
<template> <div> <Son @plus="plus"/> </div> </template> <script setup> import { reactive, ref, toRefs } from "vue"; import Son from "./Son.vue" let num = ref(100); const plus = ()=>{ num.value++; } </script>
子組件
<template> <div> <button @click="add">點我</button> </div> </template> <script setup> import { ref,defineEmits } from "vue" const num=ref(1) const emits = defineEmits(['num'])//定義號要子傳父 const add=()=>{ emits('plus',num.value) } </script>
到此這篇關(guān)于vue中setup語法糖寫法實例的文章就介紹到這了,更多相關(guān)vue setup語法糖內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue3?setup語法糖之組件傳參(defineProps、defineEmits、defineExpose)示例詳
defineProps?和?defineEmits?都是只能在?<script?setup>?中使用的編譯器宏,他們不需要導(dǎo)入,且會隨著?<script?setup>?的處理過程一同被編譯掉,這篇文章主要介紹了vue3?setup語法糖之組件傳參(defineProps、defineEmits、defineExpose)示例詳解,需要的朋友可以參考下2023-01-01vue計算屬性時v-for處理數(shù)組時遇到的一個bug問題
這篇文章主要介紹了在做vue計算屬性,v-for處理數(shù)組時遇到的一個bug 問題,需要的朋友可以參考下2018-01-01