第Ⅷ章-Ⅱ 组合式API使用

ops/2024/9/23 5:45:11/

第Ⅷ章-Ⅱ 组合式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.ppmy.cn/ops/35344.html

相关文章

设计网页用什么软件

在设计网页时&#xff0c;可以使用多种软件来完成不同的任务。以下是一些常用的网页设计软件&#xff0c;以及它们的特点和用途。 1. Adobe Photoshop&#xff1a; Adobe Photoshop 是一款功能强大的图像编辑软件。在网页设计中&#xff0c;它常用于创建和编辑网页所需的图像、…

【LangChain系列 14】语言模型概述

本文速读 LLMs 对话模型 LangChain集成了两种语言模型&#xff1a; LLM&#xff1a;输入文本&#xff0c;返回文本 对话模型&#xff1a;基于LLM&#xff0c;输入Message列表&#xff0c;返回一条Message LLM和对话模型之间有着细微且重要的不同。在LangChain中&#xff0…

安卓应用开发(一):工具与环境

开发工具 Android Studio&#xff0c;用于开发 Android 应用的官方集成开发环境 (IDE)。包括以下功能&#xff1a; 基于Gradle的构建系统 gradle是一个项目构建工具&#xff0c;将源工程打包构建为apk 安卓模拟器统一环境代码编辑模拟器实时更新Github集成Lint功能&#xff0…

Elasticsearch:如何使用 Java 对索引进行 ES|QL 的查询

在我之前的文章 “Elasticsearch&#xff1a;对 Java 对象的 ES|QL 查询”&#xff0c;我详细介绍了如何使用 Java 来对 ES|QL 进行查询。对于不是很熟悉 Elasticsearch 的开发者来说&#xff0c;那篇文章里的例子还是不能单独来进行运行。在今天的这篇文章中&#xff0c;我来详…

unittest_parameterized批量测试测试用例

import unittest from parameterized import parameterizeddef add(x, y):return xy"""问题&#xff1a;如果有三组数据需要测试&#xff1f;[(1,1,2), (1,2,3), (0,3,3)] """def get_data():return [(1, 2, 3), (3, 0, 3), (2, 1, 3)]# 定义测试…

Java苍穹外卖04-

一、缓存菜品 1.问题说明 2.实现思路 就是点击到这个分类的时候就可以展示相应的菜品数据 3.代码实现 在user的菜品的contoller中&#xff1a;增加判断redis中是否存在所需数据&#xff0c;不存在添加&#xff0c;存在直接取得 这里注意&#xff1a;你放进去用的是List<Di…

OpenHarmony实战开发-管理位置权限

Web组件提供位置权限管理能力。开发者可以通过onGeolocationShow()接口对某个网站进行位置权限管理。Web组件根据接口响应结果&#xff0c;决定是否赋予前端页面权限。获取设备位置&#xff0c;需要开发者配置ohos.permission.LOCATION&#xff0c;ohos.permission.APPROXIMATE…

【Axure高保真原型】动态伸缩信息架构图

今天和大家分享动态伸缩信息架构图的原型模板&#xff0c;我们可以通过点击加减按钮来展开或收起子内容&#xff0c;具体效果可以点击下方视频观看或者打开预览地址来体验 【原型效果】 【Axure高保真原型】动态伸缩信息架构图 【原型预览含下载地址】 https://axhub.im/ax9/…