vue3 createApp内联根组件有哪些参数

import {ref,createApp } from 'vue' const app = createApp({ /* 根组件选项 */
  data() {
    return { count: 0 };
  },
  computed: {
    doubleCount() {
      return this.count * 2;
    }
  },
  methods: {
    increment() {
      this.count++;
    }
  },
  watch: {
    count(newVal) {
      console.log(`Count changed to ${newVal}`);
    }
  },
// 生命周期钩子
  created() {
    console.log('Component created');
  },
  mounted() {
    console.log('DOM mounted');
  },
  template: '<button @click="count++">{{ count }}</button>',
  // 或使用render函数(JSX).rander函数优先级大于template
  render() {
    return h('button', { onClick: () => this.count++ }, this.count);
  },
  components: { ChildComponent },
  directives: {
    focus: {
      mounted(el) {
        el.focus();
      }
    }
  },
  provides: {
    theme: 'dark'
  },
  emits: ['submit'], // 声明自定义事件
  setup(props, { emit }) {
    const handleClick = () => {
      emit('submit', 'data');
    };
const count = ref(0) return { count, handleClick };  // template中可以使用count, handleClick
    // 渲染函数优先级高于template
return () => h('div', [ h('p', `Count: ${count.value}`), h('button', { onClick: () => count.value++ }, 'Increment') ]);
  }
})
app.mount('#app');

注意事项

  1. Composition API:若使用setup,可替代datamethods等选项(推荐在复杂逻辑中使用)。

  2. 全局配置createApp后可通过app.use()app.component()等注册全局插件或组件。

 

setup 函数的基本作用

  • 入口点:在组件初始化时执行,早于 beforeCreate 生命周期。

  • 返回值:可以返回两种内容:

    • 响应式数据:供模板或其它选项使用。

    • 渲染函数:直接控制组件的渲染(类似 render 选项)。

setup注意事项:

  1. this 不可用setup 中无法访问 this(因为它在组件实例创建前执行)。

  2. 生命周期钩子:使用 onXxx 函数(如 onMounted)替代 mounted 等选项。

 

自定义Hook的使用

// useCounter.js
import { ref } from 'vue';

export function useCounter(initialValue = 0) {
  const count = ref(initialValue);
  const increment = () => count.value++;
  return { count, increment };
}

// 组件中使用
setup() {
  const { count, increment } = useCounter();
  return { count, increment };
}

hook注意事项:

1. 响应式数据解构
直接解构 reactive 对象会失去响应性,但对 ref 无影响(如上例中的 count 是 ref)。

// 错误:解构reactive会失去响应性
const { user } = useUser(); // 假设user是reactive
// 正确:使用toRefs保持响应性
const { user } = toRefs(useUser());

2. 生命周期整合

若 Hook 中包含生命周期逻辑(如 onMounted),会自动绑定到调用它的组件。

 

1. 如何实现多组件共用 useCounter

将 useCounter 放在一个公共文件中(通常放在 src/composables/ 或 src/hooks/ 目录):

// src/composables/useCounter.js
import { ref } from 'vue';

export function useCounter(initialValue = 0) {
  const count = ref(initialValue);
  const increment = () => count.value++;
  const decrement = () => count.value--;

  return { count, increment, decrement };
}

步骤 2:在不同组件中引入

<!-- ComponentA.vue -->
<script setup>
import { useCounter } from '@/composables/useCounter';
const { count, increment } = useCounter(10); // 初始值10
</script>

<template>
  <button @click="increment">A: {{ count }}</button>
</template>

<!-- ComponentB.vue -->
<script setup>
import { useCounter } from '@/composables/useCounter';
const { count, increment } = useCounter(5); // 初始值5
</script>

2. 共用时的关键特性

特性说明
状态独立 每个组件调用 useCounter() 会创建独立的响应式数据(count 不共享)。
逻辑复用 所有组件共享同一套逻辑代码(如 increment 方法),但数据隔离。
灵活配置 可通过参数(如 initialValue)定制不同组件的初始状态。

3. 如果需要共享状态怎么办?

使用pinia

 

Hook注意事项:

1. 避免意外共享状态

  • 如果直接在 Hook 中定义全局变量(如 const count = ref(0)),会导致状态共享(不推荐!)。

  • 正确做法:始终在 Hook 函数内声明响应式数据(如 ref/reactive)。就是count要在useCounter中定义 


const count = ref(0)  // 错误
const useCount(){
  const count = ref(0)   // count要在useCounter中定义 
  return { count };
}

2. 性能优化:

对于复杂逻辑的 Hook,可以使用 computed 或 watch 减少重复计算

 

posted @ 2025-04-03 00:14  心意12  阅读(74)  评论(0)    收藏  举报