Vue3框架焦点功能点响应式数据reactive、组合式API setup、computed、组件 ...

打印 上一主题 下一主题

主题 989|帖子 989|积分 2967

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
记录几个Vue3框架焦点功能点,例如响应式数据reactive、组合式API setup、computed、组件通信、路由导航,状态管理vuex、pinia……等实战示例代码:
一、响应式数据(Reactive Data)

  • 创建响应式对象

    • 利用reactive函数创建一个响应式的对象。
    1. import { reactive } from 'vue';
    2. const state = reactive({
    3.   count: 0,
    4.   message: 'Hello Vue3'
    5. });
    6. // 在组件中使用
    7. export default {
    8.   setup() {
    9.     return { state };
    10.   }
    11. };
    复制代码
      

    • 在模板中可以直接利用{{state.count}}和{{state.message}}来显示数据,并且当这些数据发生变化时,视图会自动更新。

  • 响应式数组操作

    • 对于数组的操作,Vue3也能正确追踪变化。
    1. const list = reactive([1, 2, 3]);
    2. function addItem() {
    3.   list.push(list.length + 1);
    4. }
    复制代码

二、组合式API(Composition API) - setup函数

  • 盘算属性(Computed Properties)

    • 盘算属性基于响应式数据进行盘算并缓存结果。
    1. import { reactive, computed } from 'vue';
    2. const state = reactive({
    3.   firstName: 'John',
    4.   lastName: 'Doe'
    5. });
    6. const fullName = computed(() => `${state.firstName} ${state.lastName}`);
    7. export default {
    8.   setup() {
    9.     return { state, fullName };
    10.   }
    11. };
    复制代码

  • 生命周期钩子(Lifecycle Hooks)

    • 在setup函数中利用生命周期钩子。
    1. import { onMounted } from 'vue';
    2. export default {
    3.   setup() {
    4.     onMounted(() => {
    5.       console.log('Component is mounted');
    6.     });
    7.   }
    8. };
    复制代码

三、组件通信

  • 父子组件通信 - Props和Emit

    • 父组件传递数据给子组件(Props)。
    • 子组件发送事件给父组件(Emit)。
    • 父组件:
    1. <template>
    2.   <ChildComponent :message="parentMessage" @childEvent="handleChildEvent" />
    3. </template>
    4. <script>
    5. import { ref } from 'vue';
    6. import ChildComponent from './ChildComponent.vue';
    7. export default {
    8.   components: { ChildComponent },
    9.   setup() {
    10.     const parentMessage = ref('Hello from parent');
    11.     const handleChildEvent = (data) => {
    12.       console.log('Received from child:', data);
    13.     };
    14.     return { parentMessage, handleChildEvent };
    15.   }
    16. };
    17. </script>
    复制代码
      

    • 子组件:
    1. <template>
    2.   <button @click="sendToParent">Send to Parent</button>
    3. </template>
    4. <script>
    5. import { defineComponent, toRefs } from 'vue';
    6. export default defineComponent({
    7.   props: {
    8.     message: String
    9.   },
    10.   setup(props, { emit }) {
    11.     const { message } = toRefs(props);
    12.     const sendToParent = () => {
    13.       emit('childEvent', 'Hello from child');
    14.     };
    15.     return { sendToParent, message };
    16.   }
    17. });
    18. </script>
    复制代码

四、路由(Vue Router)集成(以下代码条件必要先安装设置好Vue Router)

  • 定义路由和导航

    • 在router/index.js中定义路由。
    1. import { createRouter, createWebHistory } from 'vue-router';
    2. import Home from '../views/Home.vue';
    3. import About from '../views/About.vue';
    4. const routes = [
    5.   { path: '/', component: Home },
    6.   { path: '/about', component: About }
    7. ];
    8. const router = createRouter({
    9.   history: createWebHistory(),
    10.   routes
    11. });
    12. export default router;
    复制代码
      

    • 在组件中进行导航。
    1. <template>
    2.   <button @click="navigateToAbout">Go to About</button>
    3. </template>
    4. <script>
    5. import { useRouter } from 'vue-router';
    6. export default {
    7.   setup() {
    8.     const router = useRouter();
    9.     const navigateToAbout = () => {
    10.       router.push('/about');
    11.     };
    12.     return { navigateToAbout };
    13.   }
    14. };
    15. </script>
    复制代码

五、状态管理工具 - Vuex与Pinia
在Vue3中,除了组件内部的状态管理,我们经常必要处理跨组件的共享状态。这时,我们可以利用Vuex或Pinia如许的状态管理工具。

  • Vuex的利用
首先,安装Vuex:
  1. npm install vuex@next --save
复制代码
创建一个Vuex store:
  1. // store/index.js
  2. import { createStore } from 'vuex';
  3. export default createStore({
  4.   state() {
  5.     return {
  6.       count: 0
  7.     };
  8.   },
  9.   mutations: {
  10.     increment(state) {
  11.       state.count++;
  12.     }
  13.   },
  14.   actions: {
  15.     increment(context) {
  16.       context.commit('increment');
  17.     }
  18.   },
  19.   getters: {
  20.     doubleCount(state) {
  21.       return state.count * 2;
  22.     }
  23.   }
  24. });
复制代码
在主文件中引入并利用store:
  1. // main.js
  2. import { createApp } from 'vue';
  3. import App from './App.vue';
  4. import store from './store';
  5. const app = createApp(App);
  6. app.use(store);
  7. app.mount('#app');
复制代码
在组件中利用Vuex:
  1. <template>
  2.   <div>
  3.     <p>Count: {{ count }}</p>
  4.     <p>Double Count: {{ doubleCount }}</p>
  5.     <button @click="increment">Increment</button>
  6.   </div>
  7. </template>
  8. <script>
  9. import { mapState, mapGetters, mapActions } from 'vuex';
  10. export default {
  11.   computed: {
  12.     ...mapState(['count']),
  13.     ...mapGetters(['doubleCount'])
  14.   },
  15.   methods: {
  16.     ...mapActions(['increment'])
  17.   }
  18. };
  19. </script>
复制代码

  • ** Pinia的利用**
Pinia是Vue的官方状态管理库,它更加轻量且与Vue3的组合式API完美集成。
首先,安装Pinia:
  1. npm install pinia --save
复制代码
创建一个Pinia store:
  1. // stores/counter.js
  2. import { defineStore } from 'pinia';
  3. export const useCounterStore = defineStore('counter', {
  4.   state: () => ({
  5.     count: 0
  6.   }),
  7.   actions: {
  8.     increment() {
  9.       this.count++;
  10.     }
  11.   },
  12.   getters: {
  13.     doubleCount: (state) => state.count * 2
  14.   }
  15. });
复制代码
在主文件中引入并利用Pinia:
  1. // main.js
  2. import { createApp } from 'vue';
  3. import App from './App.vue';
  4. import { createPinia } from 'pinia';
  5. const app = createApp(App);
  6. app.use(createPinia());
  7. app.mount('#app');
复制代码
在组件中利用Pinia:
  1. <template>
  2.   <div>
  3.     <p>Count: {{ counter.count }}</p>
  4.     <p>Double Count: {{ counter.doubleCount }}</p>
  5.     <button @click="counter.increment">Increment</button>
  6.   </div>
  7. </template>
  8. <script>
  9. import { useCounterStore } from '../stores/counter';
  10. export default {
  11.   setup() {
  12.     const counter = useCounterStore();
  13.     return { counter };
  14.   }
  15. };
  16. </script>
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

何小豆儿在此

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表