当前位置: 首页 > news >正文

第Ⅷ章-Ⅱ 组合式API使用

第Ⅷ章-Ⅱ 组合式API使用

  • provide与inject的使用
  • vue 生命周期的用法
  • 编程式路由的使用
  • vuex的使用
  • 获取DOM的使用
  • setup语法糖
    • setup语法糖的基本结构
    • 响应数据的使用
    • 其它语法的使用
    • 引入组件的使用
  • 父组件传值的使用
    • defineProps 父传子
    • defineEmits 子传父

provide与inject的使用

provide 与 inject 是 Vue 3 中用于跨组件树传递数据的 API,适合解决深层嵌套组件的通信问题。

  • provide:父组件提供数据。
  • inject:子组件接收数据。
<!-- src/App.vue -->
<template><div><ProviderComponent /></div>
</template><script setup>
import ProviderComponent from './components/ProviderComponent.vue';
</script>
<!-- src/components/ProviderComponent.vue -->
<template><div><h1>Provider Component</h1><ChildComponent /></div>
</template><script setup>
import { provide } from 'vue';
import ChildComponent from './ChildComponent.vue';const providedData = 'Hello from Provider!';
provide('message', providedData);
</script>
<!-- src/components/ChildComponent.vue -->
<template><div><h2>Child Component</h2><p>{{ message }}</p></div>
</template><script setup>
import { inject } from 'vue';const message = inject<string>('message', 'Default Message');
</script>

vue 生命周期的用法

Vue 3 引入了组合式 API,使得生命周期钩子以函数形式使用,增加了灵活性。

<template><div>{{ message }}</div>
</template><script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue';const message = ref('Hello, Vue 3!');onMounted(() => {console.log('Component is mounted');message.value = 'Component Mounted';
});onBeforeUnmount(() => {console.log('Component is about to unmount');
});
</script>

编程式路由的使用

Vue Router 支持编程式路由跳转,可以使用 router.push 和 router.replace。

<!-- src/components/NavigationComponent.vue -->
<template><div><button @click="goToHome">Go to Home</button><button @click="replaceWithAbout">Replace with About</button><button @click="goBack">Go Back</button></div>
</template><script setup>
import { useRouter } from 'vue-router';const router = useRouter();const goToHome = () => {router.push('/home');
};const replaceWithAbout = () => {router.replace('/about');
};const goBack = () => {router.go(-1);
};
</script>

vuex的使用

Vuex 是 Vue 官方的状态管理库,通常使用 createStore 创建全局 store。

// src/store/index.ts
import { createStore } from 'vuex';interface State {count: number;
}const store = createStore<State>({state: {count: 0},mutations: {increment(state) {state.count += 1;},decrement(state) {state.count -= 1;}},actions: {incrementAsync({ commit }) {setTimeout(() => {commit('increment');}, 1000);}},getters: {doubleCount(state) {return state.count * 2;}}
});export default store;

在组件中使用 Vuex 状态和方法

<!-- src/components/CounterComponent.vue -->
<template><div><h2>Counter Example</h2><p>Count: {{ count }}</p><p>Double Count (getter): {{ doubleCount }}</p><button @click="increment">Increment</button><button @click="decrement">Decrement</button><button @click="incrementAsync">Increment Async</button></div>
</template><script setup lang="ts">
import { computed } from 'vue';
import { useStore } from 'vuex';const store = useStore();const count = computed(() => store.state.count);
const doubleCount = computed(() => store.getters.doubleCount);
const increment = () => store.commit('increment');
const decrement = () => store.commit('decrement');
const incrementAsync = () => store.dispatch('incrementAsync');
</script>

获取DOM的使用

在组合式 API 中可以使用 ref 和 onMounted 钩子来访问 DOM 元素。

<template><div><input type="text" ref="inputElement" placeholder="Type something..." /><button @click="focusInput">Focus Input</button></div>
</template><script setup lang="ts">
import { ref, onMounted } from 'vue';const inputElement = ref<HTMLInputElement | null>(null);const focusInput = () => {inputElement.value?.focus();
};onMounted(() => {console.log('Component Mounted and DOM is ready');
});
</script>

setup语法糖

setup 语法糖 在 Vue 3.3 中引入,它简化了 setup 函数的使用,使得代码更加简洁易读。

setup语法糖的基本结构

<template><div>{{ message }}</div><button @click="increment">Increment: {{ count }}</button>
</template><script setup>
import { ref } from 'vue';const message = ref('Hello, Vue 3!');
const count = ref(0);const increment = () => {count.value++;
};
</script>

响应数据的使用

  • ref:创建单一响应式值。
  • reactive:创建响应式对象。
  • toRefs:将 reactive 对象转换为 ref 对象。
<template><div><p>{{ message }}</p><p>Counter: {{ count }}</p></div>
</template><script setup>
import { ref, reactive, toRefs } from 'vue';const message = ref('Hello, Vue 3!');
const state = reactive({ count: 0 });const { count } = toRefs(state);
</script>

其它语法的使用

  • computed:创建计算属性。
  • watch:观察响应式数据的变化并执行副作用。
<template><div><p>Double Count: {{ doubleCount }}</p><input v-model="name" placeholder="Name" /><p>{{ name }}</p></div>
</template><script setup>
import { ref, computed, watch } from 'vue';const count = ref(2);
const doubleCount = computed(() => count.value * 2);const name = ref('Alice');
watch(name, (newValue, oldValue) => {console.log(`Name changed from ${oldValue} to ${newValue}`);
});
</script>

引入组件的使用

<!-- src/App.vue -->
<template><CounterComponent />
</template><script setup>
import CounterComponent from './components/CounterComponent.vue';
</script>

父组件传值的使用

defineProps 父传子

<!-- src/components/ChildComponent.vue -->
<template><p>{{ message }}</p>
</template><script setup>
import { defineProps } from 'vue';const props = defineProps({message: String
});
</script>
<!-- src/App.vue -->
<template><ChildComponent message="Hello, Child!" />
</template><script setup>
import ChildComponent from './components/ChildComponent.vue';
</script>

defineEmits 子传父

<!-- src/components/ChildComponent.vue -->
<template><button @click="sendMessage">Send Message to Parent</button>
</template><script setup>
import { defineEmits } from 'vue';const emit = defineEmits(['message']);const sendMessage = () => {emit('message', 'Hello from Child Component!');
};
</script>
<!-- src/App.vue -->
<template><ChildComponent @message="handleMessage" /><p>{{ parentMessage }}</p>
</template><script setup>
import { ref } from 'vue';
import ChildComponent from './components/ChildComponent.vue';const parentMessage = ref('');const handleMessage = (msg: string) => {parentMessage.value = msg;
};
</script>
http://www.lryc.cn/news/347925.html

相关文章:

  • stable-diffusion-webui配置
  • 1+X电子商务数据采集渠道及工具选择(二)||电商数据采集API接口
  • apinto OpenAPI
  • XYCTF - web
  • 学习方法的重要性
  • 把现有的 Jenkins 容器推送到一个新的镜像标签,并且重新启动新的容器
  • 难以重现的 Bug如何处理
  • 我与足球的故事 | 10年的热爱 | 伤病 | 悔恨 | 放弃 or 继续 | 小学生的碎碎念罢了
  • js图片回显的方法
  • Java中的maven的安装和配置
  • 轴承制造企业“数智化”突破口
  • UIButton案例之添加动画
  • C#链接数据库、操作sql、选择串口
  • 本地搭建各大直播平台录屏服务结合内网穿透工具实现远程管理录屏任务
  • macos使用yarn创建vite时出现Usage Error: The nearest package directory问题
  • 【JAVA入门】Day04 - 方法
  • 前端报错 SyntaxError: Unexpected number in JSON at position xxxx at JSON.parse
  • Mybatis进阶详细用法
  • Android 系统省电软件分析
  • 了解什么是Docker
  • ChatGPT开源的whisper音频生成字幕
  • 融知财经:期货和现货的区别是什么?哪个风险大?
  • Android Studio开发之路(十)app中使用aar以及报错记录
  • sql-行转列3(转置)
  • MATLAB | 最新版MATLAB绘图速查表来啦!!
  • web安全之登录框渗透骚姿势,新思路
  • 无人机+自组网:空地点对点无人机通信解决方案
  • android TV app适配遥控器思路,recycleview选中放大
  • python篇-cmd 执行pip命令失败,但执行pyhon命令正常
  • Redis系列-3 Redis缓存问题