马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
x
记录几个Vue3框架焦点功能点,例如响应式数据reactive、组合式API setup、computed、组件通信、路由导航,状态管理vuex、pinia……等实战示例代码:
一、响应式数据(Reactive Data)
- 创建响应式对象
- import { reactive } from 'vue';
- const state = reactive({
- count: 0,
- message: 'Hello Vue3'
- });
- // 在组件中使用
- export default {
- setup() {
- return { state };
- }
- };
复制代码
- 在模板中可以直接利用{{state.count}}和{{state.message}}来显示数据,并且当这些数据发生变化时,视图会自动更新。
- 响应式数组操作
- const list = reactive([1, 2, 3]);
- function addItem() {
- list.push(list.length + 1);
- }
复制代码
二、组合式API(Composition API) - setup函数
- 盘算属性(Computed Properties)
- import { reactive, computed } from 'vue';
- const state = reactive({
- firstName: 'John',
- lastName: 'Doe'
- });
- const fullName = computed(() => `${state.firstName} ${state.lastName}`);
- export default {
- setup() {
- return { state, fullName };
- }
- };
复制代码
- 生命周期钩子(Lifecycle Hooks)
- import { onMounted } from 'vue';
- export default {
- setup() {
- onMounted(() => {
- console.log('Component is mounted');
- });
- }
- };
复制代码
三、组件通信
- 父子组件通信 - Props和Emit
- 父组件传递数据给子组件(Props)。
- 子组件发送事件给父组件(Emit)。
- 父组件:
- <template>
- <ChildComponent :message="parentMessage" @childEvent="handleChildEvent" />
- </template>
- <script>
- import { ref } from 'vue';
- import ChildComponent from './ChildComponent.vue';
- export default {
- components: { ChildComponent },
- setup() {
- const parentMessage = ref('Hello from parent');
- const handleChildEvent = (data) => {
- console.log('Received from child:', data);
- };
- return { parentMessage, handleChildEvent };
- }
- };
- </script>
复制代码
- <template>
- <button @click="sendToParent">Send to Parent</button>
- </template>
- <script>
- import { defineComponent, toRefs } from 'vue';
- export default defineComponent({
- props: {
- message: String
- },
- setup(props, { emit }) {
- const { message } = toRefs(props);
- const sendToParent = () => {
- emit('childEvent', 'Hello from child');
- };
- return { sendToParent, message };
- }
- });
- </script>
复制代码
四、路由(Vue Router)集成(以下代码条件必要先安装设置好Vue Router)
- 定义路由和导航
- import { createRouter, createWebHistory } from 'vue-router';
- import Home from '../views/Home.vue';
- import About from '../views/About.vue';
- const routes = [
- { path: '/', component: Home },
- { path: '/about', component: About }
- ];
- const router = createRouter({
- history: createWebHistory(),
- routes
- });
- export default router;
复制代码
- <template>
- <button @click="navigateToAbout">Go to About</button>
- </template>
- <script>
- import { useRouter } from 'vue-router';
- export default {
- setup() {
- const router = useRouter();
- const navigateToAbout = () => {
- router.push('/about');
- };
- return { navigateToAbout };
- }
- };
- </script>
复制代码
五、状态管理工具 - Vuex与Pinia
在Vue3中,除了组件内部的状态管理,我们经常必要处理跨组件的共享状态。这时,我们可以利用Vuex或Pinia如许的状态管理工具。
首先,安装Vuex:
- npm install vuex@next --save
复制代码 创建一个Vuex store:
- // store/index.js
- import { createStore } from 'vuex';
- export default createStore({
- state() {
- return {
- count: 0
- };
- },
- mutations: {
- increment(state) {
- state.count++;
- }
- },
- actions: {
- increment(context) {
- context.commit('increment');
- }
- },
- getters: {
- doubleCount(state) {
- return state.count * 2;
- }
- }
- });
复制代码 在主文件中引入并利用store:
- // main.js
- import { createApp } from 'vue';
- import App from './App.vue';
- import store from './store';
- const app = createApp(App);
- app.use(store);
- app.mount('#app');
复制代码 在组件中利用Vuex:
- <template>
- <div>
- <p>Count: {{ count }}</p>
- <p>Double Count: {{ doubleCount }}</p>
- <button @click="increment">Increment</button>
- </div>
- </template>
- <script>
- import { mapState, mapGetters, mapActions } from 'vuex';
- export default {
- computed: {
- ...mapState(['count']),
- ...mapGetters(['doubleCount'])
- },
- methods: {
- ...mapActions(['increment'])
- }
- };
- </script>
复制代码 Pinia是Vue的官方状态管理库,它更加轻量且与Vue3的组合式API完美集成。
首先,安装Pinia:
创建一个Pinia store:
- // stores/counter.js
- import { defineStore } from 'pinia';
- export const useCounterStore = defineStore('counter', {
- state: () => ({
- count: 0
- }),
- actions: {
- increment() {
- this.count++;
- }
- },
- getters: {
- doubleCount: (state) => state.count * 2
- }
- });
复制代码 在主文件中引入并利用Pinia:
- // main.js
- import { createApp } from 'vue';
- import App from './App.vue';
- import { createPinia } from 'pinia';
- const app = createApp(App);
- app.use(createPinia());
- app.mount('#app');
复制代码 在组件中利用Pinia:
- <template>
- <div>
- <p>Count: {{ counter.count }}</p>
- <p>Double Count: {{ counter.doubleCount }}</p>
- <button @click="counter.increment">Increment</button>
- </div>
- </template>
- <script>
- import { useCounterStore } from '../stores/counter';
- export default {
- setup() {
- const counter = useCounterStore();
- return { counter };
- }
- };
- </script>
复制代码 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |