1. 程式人生 > 實用技巧 >vue3.0實現資料的雙向繫結

vue3.0實現資料的雙向繫結

1.字串、數字

<template>
    <button @click="add">{{ num }}</button>
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue'
export default defineComponent({
    setup() {
       let num = ref(0)
       const add = () => {
           num.value = num + 1
       }
       return {
          num,
          add
       }
    }
})
</script>            

2.物件、陣列

<template>
    <button @click="addObjNum">{{ obj }}</button>
    <button @click="addArrNum">{{ arr }}</button>
</template>
<script lang="ts">
import { defineComponent, reactive } from 'vue'
export default defineComponent({
    setup() {
       let obj = reactive({
            num: 1
        })
       let obj = reactive([0])
       const addObjNum = () => {
           obj.num = obj.num + 1
       }
       const addArrNum = () => {
           arr[0] = arr[0] + 1
       }
       return {
          obj,
          arr,
          addObjNum,
          addArrNum
       }
    }
})
</script>