Vue.js 学习笔记(三)

6. Vue.js 与后端集成

使用Axios进行HTTP请求

安装与配置

npm install axios

发送GET/POST请求

import axios from 'axios';

new Vue({
  el: '#app',
  data: {
    message: ''
  },
  methods: {
    fetchData() {
      axios.get('https://api.example.com/data')
        .then(response => {
          this.message = response.data.message;
        })
        .catch(error => {
          console.error(error);
        });
    },
    postData() {
      axios.post('https://api.example.com/data', {
        message: 'Hello from Vue!'
      })
        .then(response => {
          console.log(response);
        })
        .catch(error => {
          console.error(error);
        });
    }
  }
});

与RESTful API集成

获取数据

fetchData() {
  axios.get('https://api.example.com/data')
    .then(response => {
      this.items = response.data.items;
    })
    .catch(error => {
      console.error(error);
    });
}

提交数据

postData() {
  axios.post('https://api.example.com/data', this.newItem)
    .then(response => {
      this.items.push(response.data.item);
      this.newItem = {};
    })
    .catch(error => {
      console.error(error);
    });
}

与GraphQL集成

使用Apollo Client

npm install @apollo/client graphql

查询与变更

import { ApolloClient, InMemoryCache } from '@apollo/client/core';
import { gql } from '@apollo/client/core';

const client = new ApolloClient({
  uri: 'https://api.example.com/graphql',
  cache: new InMemoryCache()
});

client.query({
  query: gql`
    query {
      posts {
        title
        content
      }
    }
  `
}).then(response => {
  console.log(response.data.posts);
});

client.mutate({
  mutation: gql`
    mutation CreatePost($title: String!, $content: String!) {
      createPost(title: $title, content: $content) {
        id
        title
        content
      }
    }
  `,
  variables: {
    title: 'Hello',
    content: 'Hello from Vue!'
  }
}).then(response => {
  console.log(response.data.createPost);
});

7. Vue.js 性能优化

代码分割与懒加载

路由懒加载

const Home = () => import('@/components/Home.vue');

export default new Router({
  routes: [
    {
      path: '/',
      name: 'Home',
      component: Home
    }
  ]
});

组件懒加载

<template>
  <div>
    <lazy-component></lazy-component>
  </div>
</template>

<script>
  export default {
    components: {
      'lazy-component': () => import('@/components/LazyComponent.vue')
    }
  };
</script>

使用Vue Devtools进行调试

Vue Devtools 是一个浏览器插件,可以帮助你调试 Vue 应用。它提供了检查组件树、时间旅行调试、性能分析等功能。

性能监控与分析
  • 使用 vue.config.js 配置性能分析
  • 使用 webpack-bundle-analyzer 分析打包体积

8. Vue.js 项目实战

项目结构设计

一个典型的 Vue 项目结构如下:

my-vue-project/
├── public/
│   ├── index.html
│   └── ...
├── src/
│   ├── assets/
│   ├── components/
│   ├── router/
│   ├── store/
│   ├── views/
│   ├── App.vue
│   └── main.js
└── ...

组件化开发

创建组件并复用。

<!-- src/components/HelloWorld.vue -->
<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  props: {
    msg: String
  }
}
</script>

<style scoped>
.hello {
  text-align: center;
  color: #42b983;
}
</style>

<!-- src/App.vue -->
<template>
  <div id="app">
    <hello-world msg="Hello, Vue!"></hello-world>
  </div>
</template>

<script>
  import HelloWorld from '@/components/HelloWorld.vue';

  export default {
    components: {
      HelloWorld
    }
  };
</script>

 

状态管理

使用 Vuex 进行状态管理。

// src/store/index.js
import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment(state) {
      state.count++;
    },
    reduction(state) {
      state.count--;
    }
  },
  actions: {},
  modules: {}
});

<!-- src/App.vue -->
<template>
  <div id="app">
    <p>{{ count }}</p>
    <button @click="increment">增加</button>
    <button @click="reduction">减少</button>
  </div>
</template>

<script>
  import { mapState, mapMutations } from 'vuex';

  export default {
    computed: mapState({
      count: state => state.count
    }),
    methods: mapMutations([
      'increment',
      'reduction'
    ])
  };
</script>

路由管理

使用 Vue Router 进行路由管理。

// src/router/index.js
import Vue from 'vue';
import Router from 'vue-router';
import Home from '@/components/Home.vue';
import About from '@/components/About.vue';

Vue.use(Router);

export default new Router({
  routes: [
    {
      path: '/',
      name: 'Home',
      component: Home
    },
    {
      path: '/about',
      name: 'About',
      component: About
    }
  ]
});

<!-- src/App.vue -->
<template>
  <div id="app">
    <router-link to="/">Home</router-link>
    <router-link to="/about">About</router-link>
    <router-view></router-view>
  </div>
</template>
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值