vue-cli 搭建项目 使用vuex、router、axios

2018-11-22  本文已影响0人  第二心跳
一、脚手架搭建项目框架: vue init webpack 项目名称
二、安装依赖插件依赖包: cnpm install 插件名 –save
-g        的意思是将模块安装到全局,具体安装到磁盘哪个位置,要看 npm config prefix 的位置。
-save     的意思是将模块安装到项目目录下,并在package文件的dependencies节点写入依赖。部署项目后必需要的模块,例如axios 等用此命令
-save-dev 的意思是将模块安装到项目目录下,并在package文件的devDependencies节点写入依赖。开发时需要的用的模块例如打包、压缩等用此命令
常用插件:
Axios       (vue版的ajax,参考下面axios)
vue-router (路由,参考下面vue-router)
vuex           (状态管理,参考下面vuex)
sass-loader(scss语法依赖)
node-sass  (scss语法依赖)
iview 或 element-ui (vue的UI组件库 可选,配置参考UI组件库)
    例如安装echarts :cnpm install echarts –save
    在main.js中添加
import echarts from 'echarts'
Vue.prototype.$echarts = echarts

三、配置路由:
    修改router /index.js 文件,所有跳转组件都要写进路由中
import Home from '@/components/home' //引入组件
routes: [  //配置路由
  {
      path: '/home',//组件路径
      name: 'home', //组件对外暴露的name
      component: Home, //引入组件时起的名字
      children: [  //子路由放在父级路由的children 数组里
          {
              path: '/index_door',
              name: 'index_door',
              component: index_door
          },
          {
              path: '/work_data',
              name: 'work_data',
              component: work_data
          }
      ]
  },
  {
      path: '/', redirect: '/home' //路由重定向
  }
]
1、  组件内通过<router-link  to=”/路由”></ router-link > 或
UI库内导航组件的 to=”/路由” 进行路由跳转
通过 <router-view></router-view> 展示路由内容,跳转和展示可以是两个兄弟组件
2、  父子组件
a.  在父组件内引入子组件
import vHeader from './vHeader'
import vMain from './vMain' //路由展示组件
import vNav from './vNav'  //路由跳转组件
b.  父组件注册子组件
    components:{
          vHeader,
             vNav,
             vMain
        },
c.  在template 中使用子组件(组件标签名不支持驼峰写法,可将驼峰写为 – 连接)
  <v-header></v-header>
<v-nav></v-nav> 
<v-main></v-main>
四、引入全局样式 参考网址:https://blog.csdn.net/smartsunsing/article/details/78529374
1、  在入口js文件main.js中引入,一些公共的样式文件
例如:import '../static/css/global.css' /*引入公共样式*/
2、  在index.html中引入link
例如:<link rel="stylesheet" href="./static/css/global.css"> /*引入公共样式*/
五、引入全局 js 
1、新建全局js,并对外暴露方法,以下两种形式
    a. export function post(){ //指定暴露方法
        逻辑代码
}
    b. export default {//默认暴露
         function a(){}
         function b(){}
}

2、在入口js文件main.js中引入
例如:import {post} from '../src/utils/common.js'
post 为 common对外暴露的方法名,如果common.js使用默认暴露,{post} 可改写为 随意单词代表该js
3、将方法挂载在vue 上
    Vue.prototype.$post = post;
4、如在公共js内使用axios 需在js内再引入一次axios
Vuex
1、安装vuex
cnpm install vuex –save
2、新建一个store文件夹(这个不是必须的),并在文件夹下新建store.js文件,文件中引入我们的vue和vuex。
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
3、在main.js 中引入新建的vuex文件
import storeConfig from './store/store.js(store.js的路径)'

4、在main.js 中添加 store
例如:new Vue({
      el: '#app',
      router,
      store,//使用store
      template: '<App/>',
      components: { App }
})
5、在 store.js 中定义 state、mutations、getters、actions 并对外暴露
const state = {//状态容器
  count: 1
}
const mutations = { //同步改变值的方法
  add(state,n){
    state.count+=n;
  },
  reduce(state){
    state.count-=1;
  }
}
const actions ={ //异步改变值的方法
  addAction(context){
    context.commit('add',10)
  },
  reduceAction({commit}){
    commit('reduce')
  }
}
const getters = { //组件获取值之前的方法
  count:function(state){
    return state.count +=100;
  }
}
export default new vuex.Store({//对外暴露
  state, mutations, actions, getters
});
6、在组件中通过dispatch()方法调用方法来改变vuex内的值
this.store.dispatch("addAction ", "");
7、在组件中使用他好this.$store.state.变量名  来获取vuex值
data(){
  return{
     test: this.$store.state.name
  }
},
vuex 刷新数据为空处理
1、  定义 state 下的变量 userinfo
2、  在mutations下定义方法 setInfo,传入参数state(固定参数),data,
3、方法内 
tate.userinfo = data 
设置localStorage.setItem(“userinfo”, data)    
4、通过dispatch调用 其中方法并传参
_this.$store.dispatch("方法名", "1111");
7、在监听组件内computed方法内监听userInfo
computed: {
  getUserIcons() {
    if(this.$store.state.token === ""){
      if( localStorage.getItem("token") === ""){
        this.$router.replace('/login'); 
      }else{
        this.$store.state.token = localStorage.getItem("token")
      }
    }
   // console.log(this.$store.state.token);
    return this.$store.state.token;
  }
},
8、在同组件内使用watch 监听computed定义的方法
watch:{
  getUserIcons(data){
    if( data === ""){
       this.$Message.info("登录过期,请重新登陆!");
    }
  }
}
*注:过程出现computed内监听不到情况,强制刷新浏览器或重启项目再试。
Axios
1、安装 axios  
运行:cnpm install axios –save-dev 
2、在main.js中配置 axios
import axios from 'axios' //引入axios
Vue.prototype.$axios = axios //挂载在vue 原型链上
3、在组件中使用axios
this.$axios({
        method: 'post',//get、post(此两种常用,还有其余方法参考axios API文档)
        url: url, //接口
        params: { //参数
    “name”: ”11”,
    “password”:”123456”
},
        headers: {//请求头看后端需求,可不写
          "Authorization": sessionStorage.getItem("token"),//后端要求返回token
        }
      }).then((res) => {//es6箭头函数,then方法执行请求成功操作
        resolve(res);
      }).catch(function (error) { //catch 方法执行捕捉异常操作
        reject(error)
      })
注意,axios为异步请求在函数外打印结果会为空,结果函数内不可执行return操作 ,如需return 需使用以下两种方式
方法一:使用promise
let myPromise =  new Promise(function (resolve, reject) {//实例化一个promise
      this.$axios({
        method: 'post',
        url: url,
        params: data,
        headers: {
          "Authorization": sessionStorage.getItem("token"),
        }
      }).then((res) => {
        resolve(res);// resolve为promise成功后执行方法
      }).catch(function (error) {
        reject(error) // reject为promise失败后执行方法
      })
    });
myPromise.then((res)=>{//调用实例化后的对象进行监听
    console.log(“res为成功返回结果”);
}).catch((error)=>{
console.log(“error为失败返回错误”);
})
方法二:使用callback函数
getData(url,data,setOption){//传入三个参数,第三个参数为回调函数setOption的函数名
this.$axios({//导出excle访问接口
        method: 'post',
        url: url,
        params: data, 
        headers: { 
          "Authorization": sessionStorage.getItem("token"),
        }
      }).then((res) => {
        setOption (res);//触发回调函数,并传入返回值
      }).catch(function (error) {
        reject(error)
      })
    //此处打印返回值会显示Undefined
}
setOption(data){ //接收返回值,并进行操作
    console.log(data);  //此处打印返回值会正常显示
}
Vue-router (路由)
1、安装vue-router
cnpm install vue-router –save
2、在main.js中配置
    import Vue from 'vue'
import App from './App'
import router from './router' //导入路由
import axios from 'axios'
Vue.prototype.$axios = axios
Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router, //挂载在vue上
  store,//使用store
  components: { App },
  template: '<App/>'
})
3、在router 文件夹下的index.js 内配置路由
    
import Vue from 'vue' //引入vue
import Router from 'vue-router' //引入路由
import Home from '@/components/home' //引入组件
import Login from '@/components/login'  //引入组件
Vue.use(Router)  //vue调用router
export default new Router({ //对外暴露路由
  mode: 'history', //可用浏览器的返回按钮返回历史
  routes: [  //配置路由
    {
      path:'/login',
      name:'login',
      component:Login,
},
{
  path: '/home',//组件文件名
  name: 'home', //组件对外暴露的name
  component: Home, //引入组件时起的名字
  children: [ //子组件
      {
         path: '/index_door',
         name: 'index_door',
                component: index_door
      },
      {
         path: '/work_data',
         name: 'work_data',
         component: work_data
      }]
}]
}
4、在.vue 文件内使用 
<router-link  to=”/路由”></ router-link > 或UI库内导航组件的 to=”/路由” 进行路由跳转
通过 <router-view></router-view> 展示路由内容,跳转和展示可以是两个兄弟组件



iview (element-ui 同理) 使用
1、安装ui库
    cnpm install iview –save
2、在main.js中配置
import iView from 'iview'
Vue.use(iView);
3、组件内在template 内使用UI库 标签

提示
1、  所有插件通过命令行安装后 都要在main.js中引入
2、  Js类的插件(jquery、echarts)需要挂载在vue 原型上Vue.prototype.$名字 = 引入时起的名字
3、  UI类的插件需要通过 Vue.use(); 一下
4、  router 、 store 这类特殊的插件需要在vue 实例上注册
new Vue({
  el: '#app',
  router,
  store,//使用store
  components: { App },
  template: '<App/>'
})
上一篇 下一篇

猜你喜欢

热点阅读