创建一个vue例子

1.需要环境,npm,node,vue-cli,没有的可以先去安装

2.使用命令 vue init webpack vue-demo 搭建vue项目, “vue-demo” 是你的项目名称。

è¿éåå¾çæè¿°

进入文件

cd vue-demo/

执行 npm run dev 命令,启动项目 ,查看控制台输出内容

用浏览器打开localhost:8080

运行成功!

------------------------------------------------------------------

3.接下来要配置element-ui

http://element-cn.eleme.io/2.0/

npm i element-ui 

在main.js 文档中写入,参考element文档

import Vue from 'vue'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import App from './App.vue'

Vue.use(ElementUI)

new Vue({
  el: '#app',
  render: h => h(App)
})

4.配置路由,找到router文件下的index.js文件

可参考文档

import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'

Vue.use(Router)

let routes = [{
  path: '/',
  name: 'HelloWorld',
  //component: HelloWorld   //第一种写法用import引入
  //异步加载组件路由懒加载
  // component: resolve => require(['@/components/HelloWorld'], resolve),//第二种写法,
  component: () => import('@/components/HelloWorld'),//第三种写法 Webpack 自动代码分割的异步组件
}];
let router = new Router({
  routes
});
export default router;

5.配置axios 发送请求

npm install axios

在src下,新建一个axios文件夹,创建axios.js文件配置全局axios默认值,可参考axios文档

在axios.js 中配置全局请求信息

import axios from 'axios';
//全局配置
axios.defaults.baseURL = '';
//axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
//覆盖库的超时默认值
//现在所有请求将在超时前等待2.5秒
axios.defaults.timeout = 2500;
//拦截器处理
//发送前处理
axios.interceptors.request.use(function(config){
    //例如判断是否有token
    let token=localStorage.getItem('authenticationtoken');
    if(null!=token&&typeof token!='undefined'&&token.trim!=''){
        config.headers.Authorization=token;
    }else{
        console.log('token不存在');
    }
    return config;
},function(error){
    return Promise.reject(error);
});
//添加响应拦截器
axios.interceptors.response.use(function(response){
    console.log("response:"+JSON.stringify(response));    
    return response;
},function(error){
    console.log(error);
    return Promise.reject(error,'服务器响应失败');
});

然后在main.js文件中引用配置信息

//引用axios配置信息
import axios from 'axios';
import './axios/axios'
Vue.prototype.$ajax=axios;

6.配置服务代理信息webpack的proxyTable设置跨域

在config文件下,找到index.js文件

主要配置开发环境下proxyTable里面的信息

 dev: {
    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
      '/api/': {
        // 设置你调用的接口域名和端口号          
        target: 'http://127.0.0.1:8081',
        //secure: false,  // 如果是https接口,需要配置这个参数
        changeOrigin: true, //是否跨域
        pathRewrite: {
          //'^/api/': ''          //将访问路径的api替换,后台服务不用加api了
        }
      }
    },
}

7.写一个简单的登入页面提交请求,保存token

  methods: {
      onSubmit() {
        this.$ajax.post('/api/system/login', {
            username: "13237567651",
            password: "111111"
          })
          .then(function (response) {
              //例如:response返回值为token;
              let token='eyJpZCI6MSwidGVsZXBob25lIjoiMTMyMzc1Njc2NTEiLCJwYXNzd29yZCI6IjExMTExMSIsInVzZXJuYW1lIjoiMjIyMiIsInJvbGUiOjEsImlhdCI6MTU1NTA1NjU0NiwiZXhwIjoxNTU1MTQyOTQ2fQ'
              //保存到localStorage
               localStorage.setItem('authenticationtoken',token);
            console.log(response);
          })
          .catch(function (error) {
            console.log(error);
          });
      }
    }

8.vuex store状态管理的简单应用,更多内容可参考store文档,简单例子参考vuex状态管理

npm install --save vuex

在main.js中引入store,添加一下代码即可

import Vue from 'vue'
import Vuex from 'vuex' //要引入vuex
Vue.use(Vuex)  //vue需调用vuex
实例化store
var store =new Vuex.Store({
        state:{
            //存放组件之间共享的数据
            name:"jjk"
        },
         mutations:{
             //显式的更改state里的数据
         },
         getters:{
             //过滤state数据
         },
         actions:{
             //
         }
    }); 

new Vue({
  el: '#app',
  router,
// 把 store 对象提供给 “store” 选项,这可以把 store 的实例注入所有的子组件
  store,  
  components: { App },
  template: '<App/>', 
})

在其他子vue调用

8.1.state单一状态数的调用,用一个对象就包含了全部的应用层级状态

调用的第一种应用场景

this.$store.state.name

调用的第二种写法计算属性

computed: {
    count () {
      return this.$store.state.name
    }
  }

调用的第三种写法mapState 辅助函数简化写法,这种写法在调用时,可以直接  this.name  使用;

// 在单独构建的版本中辅助函数为 Vuex.mapState
import {mapState} from 'vuex';
//简化计算属性写法
 computed:{
        ...mapState(['name','age']),
    }

8.2.Getter:可以认为是 store 的计算属性,store的值发生变化后会被重新计算

第一种Getter应用的写法:只带一个参数state

getters: {
    getname: state=> {
      return state.name;
    }
  }

第二种带多个参数的写法

getters: {
  // 将getters作为自己的参数,调用其他方法返回结果
  doneTodosCount: (state, getters) => {
    return getters.getname.length
  }
}

第三种mapGetters 辅助函数

import { mapGetters } from 'vuex'

export default {
  // ...
  computed: {
  // 使用对象展开运算符将 getter 混入 computed 对象中
    ...mapGetters([
      'doneTodosCount',
      'getname',
      // ...
    ])
  }
}

在组件访问

this.$store.getters.getname

8.3 mutation 更改 Vuex 的 store 中的状态的唯一方法是提交 mutation,mutation 都是同步事务

const store = new Vuex.Store({
  state: {
    count: 1
  },
  mutations: {
    increment (state) {
      // 变更状态
      state.count++
    },
    //传入参数 ,n可以为一个数字,也可以为一个对象:amount:10
    countAdd (state, n) {
        state.count += n;
        //state.count+=n.amount;
      }
  }
})

组件使用写法一:

this.$store.commit('increment')

mapMutations辅助函数写法二


export default {
  // ...
  methods: {
    ...mapMutations([
      'increment', // 将 `this.increment()` 映射为 `this.$store.commit('increment')`

      // `mapMutations` 也支持载荷:
      'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.commit('incrementBy', amount)`
    ]),
    ...mapMutations({
      add: 'increment' // 将 `this.add()` 映射为 `this.$store.commit('increment')`
    })
  }
}

使用

this.increment()

8.4Action 可执行异步操作

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
      state.count++
    }
  },
  actions: {
    //此处的context可以理解成与store有相同功能和属性的对象
    increment (context) {
      context.commit('increment')
    }
  }
})

分发Action

store.dispatch('increment')

在组件分发Action

this.$store.dispatch('xxx')

mapActions辅助组件

import { mapActions } from 'vuex'

export default {
  // ...
  methods: {
    ...mapActions([
      'increment', // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')`

      // `mapActions` 也支持载荷:
      'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.dispatch('incrementBy', amount)`
    ]),
    ...mapActions({
      add: 'increment' // 将 `this.add()` 映射为 `this.$store.dispatch('increment')`
    })
  }
}

8.5Module 模块化简单的写法

const moduleA = {
  state: { ... },
  mutations: { ... },
  actions: { ... },
  getters: { ... }
}
const store = new Vuex.Store({
  modules: {
    a: moduleA
  }
})

store.state.a // -> moduleA 的状态

9.项目地址:https://gitee.com/leepace/demovue.git

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值