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語法糖組件只需要導入,不需要注冊組件
<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>到此這篇關于vue中setup語法糖寫法實例的文章就介紹到這了,更多相關vue setup語法糖內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
代替Vue?Cli的全新腳手架工具create?vue示例解析
這篇文章主要為大家介紹了代替Vue?Cli的全新腳手架工具create?vue示例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-10-10
解決uniapp項目在微信開發(fā)工具里打開報錯Error:app.json:在項目根目錄未找到app.json
這篇文章主要給大家介紹了關于解決uniapp項目在微信開發(fā)工具里打開報錯Error:app.json:在項目根目錄未找到app.json的相關資料,文中通過圖文將解決的辦法介紹的非常詳細,需要的朋友可以參考下2024-03-03
vue、uniapp實現(xiàn)組件動態(tài)切換效果
在Vue中,通過使用動態(tài)組件,我們可以實現(xiàn)組件的動態(tài)切換,從而達到頁面的動態(tài)展示效果,這篇文章主要介紹了vue、uniapp實現(xiàn)組件動態(tài)切換,需要的朋友可以參考下2023-10-10

