vue2 使用vue-cli2 搭建项目

本文详细介绍如何使用vue-cli脚手架快速搭建Vue项目,并介绍了包括安装依赖、配置路由、集成Axios、引入样式预处理器(如Sass/LESS)、使用Element UI组件库、加载字体图标、以及状态管理工具VueX的配置流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


1  vue-cli  脚手架自带引用路由 

npm install --g vue-cli 全局下载脚手架

vue init webpack test 生成项目 形成基本结构

npm install 依赖包

npm run dev 启动项目


2 引用axios   

import axios from 'axios'

挂载axios  挂不挂载有不同说法

Vue.prototype.axios = axios

3  引用样式 sass或者 less

npm install less less-loader --save 


需要的话mixins混合

4  引入组件库 elementUI

安装

npm i element-ui -S  

引用注册

import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';


Vue.use(ElementUI);

5  引用字体图标库  iconFont

http://www.iconfont.cn/collections/index?spm=a313x.7781069.1998910419.3

选择要用的图标 下载代码到本地 复制到asset 文件夹里 

在main.js中引入iconfont.css样式
import './assets/iconfont/iconfont.css'

代码里使用iconfont 加上自动生成的类名

<class="iconfont icon-zitigui-xianxing"></i>

6 引入VueX

npm install vuex --save-dev

建立一个和main.js同级的store.js文件

import Vue from "vue"
import Vuex from "vuex"

Vue.use(Vuex);

const store = new Vuex.Store({
  state:{
    type: '',
  },
  getters:{
    getType:function (state) {
      // if(!state.type){
      //   state.type = localStorage.getItem('type')
      // }
      // return state.type;
    }
  },
  mutations:{
    //格式:类型(名字)+处理函数
    //加1
    // changetype(state,type) {
    //   //console.log(state)//state对象
    //   state.type = type;
    // }
  },
  actions:{
    /* increment({commit}){
       commit("INCREMENT")
     }*/
  }
});

export default store

然后在main.js中引用store.js

import store from  './assets/js/store'
  • 1

同时在vue下注册

new Vue({
  el: '#app',
  router,
  store,
  template: '<App/>',
  components: { App }
})

有两种方法可以type的值。 
a、直接调用type更改

this.$store.state.type = 'aaa'
  • 1

b、调用vuex的commit函数,官网更推荐这种方式。

this.$store.commit('changetype','aaa')
  • 1

changetype上面的store.js里已经定义了

 mutations:{
    //格式:类型(名字)+处理函数
    //加1
    changetype(state,type) {
      //console.log(state)//state对象
      state.type = type;
    }
  },
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

此时type的值就变为了aaa

4,获得type的值,也有两种方法。 
a、直接拿到type的值

this.$store.state.type
  • 1

b、使用getter方法

this.$store.getters.getType
  • 1

下面是我用vuex时遇到的一个坑。 
vuex刷新时数据丢失。 
对于一个程序来说,整个页面都是变量,刷新页面数据当然会丢失,解决方案就是使用localStorage,sessionStorage等。如代码,如果页面没有type的值,就用localStorage在设置一下type值

getters:{
    getType:function (state) {
      if(!state.type){
        state.type = localStorage.getItem('type')

      }
      return state.type;
    }
  },





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值