vue3中,實現數據驅動,在寫法上有了改變
<template> <div style="cursor:pointer;" @click="changeWord">{{world}}</div> </template> <script> import { reactive, toRefs } from 'vue'; export default { setup() { const data = reactive({ world: 'Hellow world' }); let changeWord = () => { data.world == 'Hellow world'? data.world="get out of the world":data.world ="Hellow world"; }; return { changeWord, ...toRefs(data) }; }, components: {} }; </script> <style> </style>
關鍵代碼:使用reactive包裝變量,在setup函數中結構toRefs函數返回的對象,方法直接返回便能夠被當前組件使用。
方法的綁定和vue2保持一致,但是函數聲明的位置發生了變化(當然也能繼續寫在methods中,但是這樣在使用vue3的provide和reject時可能會遇到某些問題,至於是什么,本人還在學習中,今后補充,也希望各位能夠指點)。