如何用nodejs搭建vuex?jquery封装的ajax如何实现跨域返回json格式字符

2016-12-13 5:18:03 77点热度 0人点赞 0条评论
一、Node.js环境下搭建Vuex的详细步骤 1.1 安装Vue CLI并创建项目 打开终端执行:npm install -g @vue/cli安装Vue CLI工具 创建新项目:vue create my-proje […]
  • 一、Node.js环境下搭建Vuex的详细步骤
  • 1.1 安装Vue CLI并创建项目
  • 打开终端执行:npm install -g @vue/cli安装Vue CLI工具
  • 创建新项目:vue create my-project,选择手动配置时勾选Vuex选项
  • 1.2 手动集成Vuex模块
  • 在项目根目录执行:npm install vuex --save
  • 在src目录下新建store/index.js文件
  • 配置store实例:
  • import Vue from 'vue'import Vuex from 'vuex'Vue.use(Vuex)export default new Vuex.Store({  state: {    count: 0  },  mutations: {    increment(state) {      state.count++    }  },  actions: {    increment({ commit }) {      commit('increment')    }  }})
  • 1.3 在main.js中挂载Store
  • import Vue from 'vue'import App from './App.vue'import store from './store'new Vue({  store,  render: h => h(App)}).$mount('#app')
  • 1.4 组件中使用Vuex
  • 在组件模板中访问状态:{{ $store.state.count }}
  • 通过计算属性获取状态:
  • computed: {  count() {    return this.$store.state.count  }}
  • 触发actions修改状态:
  • methods: {  addCount() {    this.$store.dispatch('increment')  }}
  • 二、jQuery Ajax实现跨域及JSON数据处理
  • 2.1 跨域基本原理
  • 同源策略限制:协议/域名/端口需完全一致
  • CORS(推荐方案):通过HTTP头部控制
  • JSONP:仅支持GET请求,依赖服务器支持
  • 2.2 CORS服务器配置示例(Express)
  • const express = require('express')const app = express()app.use((req, res, next) => {  res.header("Access-Control-Allow-Origin", "*")  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")  next()})app.get('/api/data', (req, res) => {  res.json({ message: '跨域成功' })})app.listen(3000)
  • 2.3 jQuery Ajax跨域请求示例
  • $.ajax({  url: 'http://localhost:3000/api/data',  type: 'GET',  dataType: 'json',  crossDomain: true,  success: function(response) {    console.log(response.message);  },  error: function(xhr) {    console.error('跨域失败:', xhr.statusText);  }});
  • 2.4 JSONP实现方案
  • 服务端返回JSON包裹函数:
  • app.get('/jsonp', (req, res) => {  const callback = req.query.callback;  res.send(`${callback}({ "data": "jsonp数据" })`);})
  • 客户端调用:
  • $.ajax({  url: 'http://localhost:3000/jsonp',  dataType: 'jsonp',  jsonp: 'callback',  success: function(data) {    console.log(data.data); // 输出:"jsonp数据"  }});
  • 三、常见问题与解决方案
  • 3.1 跨域请求被拦截
  • 检查服务器CORS头部配置是否完整
  • 确认请求方法与预检请求(Preflight)匹配
  • 开发环境可使用代理服务器(Vue.config.js)
  • 3.2 Vuex状态未更新
  • 避免直接修改state,必须通过mutations
  • 数组/对象修改需使用Vue.set或解构重组
  • 检查mapState/mapActions是否正确绑定
  • 3.3 JSON解析异常
  • 确保服务器返回Content-Type为application/json
  • 处理非标准JSON格式数据(如注释或换行)
  • 使用try/catch包裹解析逻辑
  • 四、最佳实践与优化建议
  • 4.1 Vuex模块化设计
  • 拆分store为独立模块:
  • // modules/user.jsconst state = { name: '' }const mutations = { setName(state, val) { state.name = val } }export default { namespaced: true, state, mutations }
  • 在根store引入模块:
  • modules: {  user: require('./modules/user').default}
  • 4.2 异步操作优化
  • 使用actions处理异步请求:
  • actions: {  async fetchData({ commit }) {    const data = await $.get('/api/data');    commit('setData', data);  }}
  • 结合axios替代jQuery.ajax:
  • import axios from 'axios'async fetchData({ commit }) {  try {    const response = await axios.get('/api/data');    commit('setData', response.data);  } catch(error) {    console.error(error);  }}
  • 4.3 性能优化技巧
  • 使用mapGetters减少计算属性冗余
  • 对频繁变化的state添加防抖处理
  • 使用Vue Devtools调试状态树
  • 生产环境开启严格模式:
  • new Vuex.Store({  strict: process.env.NODE_ENV !== 'production'})
  • 五、完整代码演示
  • 5.1 完整Vuex Store结构
  • // store/index.jsimport Vue from 'vue'import Vuex from 'vuex'import user from './modules/user'Vue.use(Vuex)export default new Vuex.Store({  state: {    globalConfig: {}  },  mutations: {    setGlobalConfig(state, config) {      Vue.set(state, 'globalConfig', config)    }  },  actions: {    initConfig({ commit }) {      $.getJSON('/api/config', (config) => {        commit('setGlobalConfig', config)      })    }  },  modules: {    user  }})
  • 5.2 组件使用示例
  • <template>  <div>    <p>用户名:{{ user.name }}</p>    <button @click="updateName">更新名称</button>  </div></template><script>import { mapState, mapMutations } from 'vuex'export default {  computed: {    ...mapState(['user'])  },  methods: {    ...mapMutations(['setName']),    updateName() {      this.setName('新名字')    }  }}</script>
  • 六、进阶扩展方向
  • 集成Redux-like状态管理方案(如Vuex-ORM)
  • 使用Vue Router与Vuex深度整合
  • 实现服务端渲染(SSR)时的状态预取
  • 通过TypeScript强化类型安全
  • 结合Vuex-Persistedstate持久化存储

PC400

这个人很懒,什么都没留下