zoukankan      html  css  js  c++  java
  • vue3.0 组合式API(Composition API)

    一、setup、ref、onMounted

    新的 setup 组件选项在创建组件之前执行

    新的 ref 函数使任何响应式变量在任何地方起作用

    合式 API 上的生命周期钩子与选项式 API 的名称相同,但前缀为 on

    <template>
      <div>
        <div>
          1
        </div>
      </div>
    </template>
    
    <script>
    import { ref, onMounted } from 'vue'
    import Api from '../api'
    
    export default {
      setup() {
        const list = ref([])
        
        const getList = () => {
          Api.list().then(res  => {
            console.log(res)
            if (res.code === 200) {
              list.value = res.data
            }
          })
        }
    
        onMounted(getList)
    
        return {
          list,
          getList
        }
    
      },
      data() {
        return {
        }
      }
    }
    </script>
    
    <style>
    
    </style>

    二、关注点分离,把相关的代码提取到独立的文件里

    List.vue:

    <template>
      <div>
        <div v-for="item in list" :key="item.id">
          {{item.title}}
        </div>
      </div>
    </template>
    
    <script>
    import useList from './useList'
    
    export default {
      setup() {
        const { list } = useList()
    
        return {
          list
        }
      },
      data() {
        return {
        }
      }
    }
    </script>
    
    <style>
    
    </style>

    useList.js:

    import { ref, onMounted } from 'vue'
    import Api from '../api'
    
    export default () => {
      const list = ref([])
    
      const getList = () => {
        Api.list().then(res  => {
          console.log(res)
          if (res.code === 200) {
            list.value = res.data
          }
        })
      }
    
      onMounted(() => getList())
    
      return {
        list,
        getList
      }
    }
  • 相关阅读:
    RabbitMQ
    操作系统复习知识
    计算机网络相关知识复习
    转帖--Linux的文件检索(locate、find、which、whereis)
    go-ioutil
    使用wrk进行压测
    03x01 Java基础语法
    02x03 Hello World!!!
    02x02 环境搭建
    02x01 Java入门
  • 原文地址:https://www.cnblogs.com/xutongbao/p/14876285.html
Copyright © 2011-2022 走看看