美文网首页
vue3学习总结

vue3学习总结

作者: b59a2ae26f20 | 来源:发表于2021-01-24 15:12 被阅读0次

    setup返回的对象数据如果想被模版正确解析,必须是一个ref函数返回的类型

    <template>
      <div>
        <h1>{{ count }}</h1>
        <div>{{double}}</div>
        <button @click="increase">add</button>
      </div>
    </template>
    
    <script lang="ts">
    import { ref, computed } from 'vue'
    export default {
      name: 'HelloWorld',
      setup () {
        const count = ref(0)
        const double = computed(() => {
          return count.value * 2
        })
        const increase = () => {
          count.value++
        }
        return {
          count,
          increase,
          double
        }
      }
    }
    </script>
    

    但此时会发现代码写起来很麻烦

    <template>
      <div>
        <h1>{{ count }}</h1>
        <div>{{double}}</div>
        <button @click="increase">add</button>
      </div>
    </template>
    
    <script lang="ts">
    import { computed, reactive, toRefs } from 'vue'
    export default {
      name: 'HelloWorld',
      setup () {
        const data = reactive({
          count: 0,
          increase: () => {
            data.count++
          },
          double: computed(() => { return data.count * 2})
        })
        const refData = toRefs(data)
        return {
          ...refData
        }
      }
    }
    </script>
    

    相关文章

      网友评论

          本文标题:vue3学习总结

          本文链接:https://www.haomeiwen.com/subject/psymzktx.html