Vue 开发总结

182 阅读1分钟

1. js文件export 和 export default的区别?

  • export:
// a.js 文件
export{
    moduleA,
    moduleB,
    ...
}

// b.js
import {moduleA, moduleB} from 'a.js'
moduleA();
moduleB();
...
  • export default:
// a.js
export default {
    moduleA,
    moduleB,
    ...
}

// b.js
import a from 'a.js'
a.moduleA();
a.moduleB();
...

2. Vue引入外部js

js文件:

function moduleA(){
    
}

export {
    moduleA
}

vue文件

import {moduleA} from xx.js

3. Vue如何引入全局js

// main.js中引入
import jq from 'jq';

Vue.prototype.$jq = jq;

// 使用
this.$jq;

4.文件设置别名

// base.conf.js
resolve:{
    alias:{
        @: resolve('scr');
        'jqurey': '../xx/jquery.js'
    }
}

5.Vuex的使用

数据流

5.1 名次解释

  • state: 存储属性
  • actions: 暴露给外部使用,通过调用mutation,来修改state
  • mutation:被actions调用,修改state
  • getter:计算属性

5.2 模块划分

为了使Vuex的数据结构更清晰,可以按照不通功能划分不通的模块。

// index.js
import Vue from 'vue'
import Vuex from 'vuex'
import order from './modules/order'
import platform from './modules/platform'
Vue.use(Vuex)

const debug = process.env.NODE_ENV !== 'production'

export default new Vuex.Store({
  modules: {
    order,
    platform
  },
  strict: debug,
})

5.3 模块实现

具体的模块实现:

/**
 * Created by fanyalong on 2018/8/29.
 */

const state = {
  orderStatus: 0,
  orderType: 0,
  questionId: 0,
}

const actions = {
  createOrder(context, order){
    context.commit('createOrder', order);
  }
}

const mutations = {
  createOrder(state,order){
    state.orderStatus = order.orderStatus;
    
    state.orderType = order.orderType;
    
    state.questionId = order.questionId;
  }
}

const getters = {
  orderCategory(state){
    var category = '';
    if (state.questionType === 0){
      category = "文字咨询";
    }else if(state.questionType === 1){
      category = "电话咨询";
    }else {
      category = "代报案";
    }
    return category;
  }
}

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
}

5.4 Vuex的使用

// 按需引入模块
import {mapActions, mapGetters, mapState} from 'vuex'

// mapActions:内部方法可以直接使用
// mapState\mapGetters:需要在computed中导出用到的state


export default{
    
     computed:{
      ...mapState({
        questionType: state => state.order.questionType,
        orderId: state => state.order.orderId,
        lawyerId: state => state.order.lawyerId,
      }),

      ...mapGetters('order',{
        category: 'orderCategory',
        price: 'orderPriceDisplay',
      })
    },
    ...
}