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
      }
    }
  • 相关阅读:
    Eclipse打jar包的方法
    Eclipse中SVN插件的安装
    无法远程访问 MySql Server
    TCP(Socket基础编程)
    安装淘宝镜像cnpm时出现问题及解决方案
    搭建vue脚手架---vue-cli
    padding和margin设置成百分比
    响应式布局
    响应式网页:用em,rem设置网页字体大小自适应
    url两次编码
  • 原文地址:https://www.cnblogs.com/xutongbao/p/14876285.html
Copyright © 2011-2022 走看看