搭建vue项目脚手架_逆战班出品

搭建vue项目脚手架

1. 安装
  • 执行以下命令(npm)
npm install @vue/cli -g//全局安装
  • 创建目录
vue create 目录文件名
  • 进入目录
cd 目录文件名
  • 启动项目
npm run serve
可在package.josn文件里面添加
"start": "npm run serve"
执行npm start启动项目 
2. 安装路由(npm)
npm install vue-router
3. 创建router.js文件

在src目录里面创建router.js文件

import Vue from 'vue'
//引入vue-router模块
import VueRouter from 'vue-router'
//使用Vue进行注册
Vue.use(VueRouter)
//配置路由
//创建一个路由实例
const router = new VueRouter({
    routes:[
		{
			path:'路由地址'
			component:'组件名'
		}
	]
})
//抛出
export default router
4. 引入组件
import 组件名 from '组件路径'
5.路由懒加载
const 组件变量名 = () => import ('组件路径')
6.嵌套路由(children)
//二级或者多级路由,使用children来嵌套路由
//二级路由嵌套
const routes = [
		{path:'/hello', component:HelloWorld},
        {path:'/films', 
        component:films,
		//二级路由嵌套
        children:[
            {
                path:'nowPlaying',
                component:NowPlaying
            },
            {
                path:'comingSoon',
                component:ComingSoon
            },
            //重定向
            {
                path:'',
                redirect:'nowPlaying'
            }
        ]
    },
]
//路由嵌套必须写在需要嵌套的代码里面
7. 重定向(redirect)
重定向也是通过 routes 配置来完成,下面例子是从 /a 重定向到 /b
const router = new VueRouter({
  routes: [
    { path: '/a', redirect: '/b' }
  ]
})
重定向的目标也可以是一个命名的路由
const router = new VueRouter({
  routes: [
    { path: '/a', redirect: { name: 'foo' }}
  ]
})
8. 两种路由的跳转方式
router-link:声明式路由跳转
注:声明式路由跳转默认在浏览器渲染成a标签
<router-link exact to="" tag="" active-class=""></router-link>
to:要跳转的路由
tag:指定在浏览器中渲染成声什么标签
active-class:用于指定高亮样式
exact:指定url路由和to值完全相当才算是匹配成功
//编程式路由跳转
this.$router.push('/film/'+item.name+'/'+item.id+'/'+item.time)
9. 前端的两种路由模式
//hash模式和history模式的区别
hash模式:url中有个#,部署至服务端没有任何问题;
history模式:url中没有#,部署至服务端后刷新页面会出现404

Vuex(状态管理模式)

1. 安装
//执行以下命令
npm install vuex -S
2. 在src目录中创建store.js文件
import Vue from 'vue';
//引入vuex模块
import Vuex from 'vuex';
//注册vuex
Vue.use(Vuex);

创建一个store实例
// store 这是Vuex所提供的用于存储数据的一个中心
// 一个应用程序,只能有一个store
// 这是一个数据仓库
const store = new Vuex.Store({
// state表示“状态”,就是应用程序中的数据
// 凡是放在state中的数据,在任何组件中都被共享和访问
// 访问方式:this.$store.state
// 一旦state中的数据发生变化,那么在所有组件中都会同步且自动地发生变化
	state:{
		 count: 100,
		    userinfo: {
		      name: '1917',
		      phone: '111111'
		    }
	}
// mutations 改变、变化的意思
// 作用:这是Vuex所推荐的改变state的唯一入口
// 业务逻辑中如果要改变state,建议把方法定义在mutations中,在使用调用这个些方法
})
mutations: {
	// 用于对count执行"加"的操作
	add(state, payload) {
		state.count += payload
	},
	// 用于对count执行"减"的操作
	sub(state, payload) {
		state.count -= payload
	}
}
//抛出
export default store
3. 在main.js文件中引入store.js
//引入vuex实例
import store from './store.js'
//在Vue根容器挂载
store,//挂载vuex
4. 把store实例中数据渲染到页面
<div>
<!-- 使用$store.state.count -->
	<h1 v-text='count'></h1>
	<button @click="subClick"></button>
</div>
//在script执行事件
<script>
// mapState的作用:把state中的数据映射进来,变成组件的自有数据
// mapMutations的作用,用于把store中的mutations方法映射进来,变成组件的自有方法
import { mapState,mapMutations } from 'vuex' 
export default {
    computed:{
        ...mapState(['count'])
    },
    methods:{
        ...mapMutations(['sub']),
        subClick(){
            // this.$store.commit('sub',20)
            this.sub(20)
        }
    }
}
5. 在store.js文件中定义数据、事件
const store = new Vuex.Store({
	// state表示“状态”,就是应用程序中的数据
    state:{
        count:100
    },
	// mutations 改变、变化的意思
	// 作用:这是Vuex所推荐的改变state的唯一入口
	// 业务逻辑中如果要改变state,建议把方法定义在mutations中,在使用调用这个些方法
    mutations:{
        add(state,payload){
            state.count += payload;
        },
        sub(state,payload){
            state.count -= payload;
        }
    }
})

vuex核心概念

1. state(单一状态树)
// state表示“状态”,就是应用程序中的数据
    // 访问方式:this.$store.state
    state:{
        count:100,
        userinfo:{
            name:"1917",
            phone:"123"
        },
        songlist:[]
    },
2. mapState 辅助函数
// 在单独构建的版本中辅助函数为 Vuex.mapState
//mapState的作用:把state中的数据映射进来,变成组件的自有数据
import { mapState } from 'vuex'
//需要渲染到页面的数据都需要使用vue计算属性computed
computed:{
        ...mapState(['songlist'])
    },
3. 对象展开运算符

mapState 函数返回的是一个对象。我们如何将它与局部计算属性混合使用呢?通常,
我们需要使用一个工具函数将多个对象合并为一个,以使我们可以将最终对象传给
computed 属性。但是自从有了对象展开运算符,我们可以极大地简化写法:

computed: {
  localComputed () { /* ... */ },
  // 使用对象展开运算符将此对象混入到外部对象中
  ...mapState({
    // ...
  })
}
4. mutations

mutations 改变、变化的意思
作用:这是Vuex所推荐的改变state的唯一入口
业务逻辑中如果要改变state,建议把方法定义在mutations中,在使用调用这个些方法

更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。Vuex 中的 mutation
非常类似于事件:每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调
函数 (handler)。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state
作为第一个参数:

const store = new Vuex.Store({
  state: {
    count: 1
  },
  //需要执行的方法都需要写在mutations里面
  mutations: {
  //传入state,payload两个参数
    increment (state,payload) {
      // 变更状态
      //state.count++
	  state.count += payload
    }
  }
})

//需要执行这个方法则需要在组件事件里methods定义方法
methods:{
    addClick(){
      this.$store.commit('increment',10)
    }
  }

说到这里,当然mutations也有mapMutations辅助函数

//mapMutations的作用,用于把store中的mutations方法映射进来,变成组件的自有方法
import { mapMutations } from 'vuex' 

methods:{
	//使用...扩展运算符
        ...mapMutations(['sub']),
        subClick(){
            // this.$store.commit('sub',20)
            this.increment(20)
        }
    }
5. actions

异步方法,比如调后端接口

//定义一个异步数据
actions:{
	getUserinfo(store){
		setTimeout(()=>{
			var userinfo = {name:"2020",phone:"123"}
			//传入组件
			store.commit('updataUserinfo',userinfo)
		},2000)
	},
},
//配置数据方法
mutations:{
	updataUserinfo(state,payload){
		state.userinfo = payload
	},
},
//在模块文件中mounted函数中接收
mounted(){
      this.$store.dispatch('getUserinfo')
    }
}

axios数据请求

1. 安装(npm)
//执行以下命令
npm install axios -S
2. 引入axios模块
//在store.js文件中引入axios
import axios from 'axios'
3. 数据请求
actions:{
	//GET请求方式
	getSonglist(store){
		//请求的url地址
		var url = 'http://localhost:8080/soso/fcgi-bin/client_search_cp?ct=24&qqmusic_ver=1298&new_json=1&remoteplace=txt.yqq.center&searchid=38015610295788532&t=0&aggr=1&cr=1&catZhida=1&lossless=0&flag_qc=0&p=1&n=10&w=%E5%91%A8%E6%9D%B0%E4%BC%A6&g_tk=1729523542&loginUin=804509646&hostUin=0&format=json&inCharset=utf8&outCharset=utf-8&notice=0&platform=yqq.json&needNewCode=0'
		axios.get(url).then(res=>{
			var list = res.data.data.song.list
			console.log("成功",list);
			store.commit('updataSonglist',list)
		}).catch(err=>{
			console.log("失败",err);
		}).then(()=>{
			console.log("总会执行");
		})
	}
}

VUE解决跨域(使用反向代理)

在文件夹根目录创建 vue.config.js 文件

如果你的前端应用和后端 API 服务器没有运行在同一个主机上,你需要在开发环境下将
API 请求代理到 API 服务器。这个问题可以通过 vue.config.js 中的 devServer.proxy
选项来配置。

devServer.proxy 可以是一个指向开发环境 API 服务器的字符串:

module.exports = {
devServer: {
proxy: ‘http://localhost:4000’
}
}

这会告诉开发服务器将任何未知请求 (没有匹配到静态文件的请求) 代理到http://localhost:4000

如果你想要更多的代理控制行为,也可以使用一个 path: options 成对的对象

module.exports = {
devServer: {
proxy: {
//’/api’:请求API的端口号后面的参数
‘/api’: {
//url:填写请求的API的协议,域名,端口号
target: ‘’,
ws: true,
changeOrigin: true
},
‘/foo’: {
target: ‘<other_url>’
}
}
}
}

最后将axios请求的url改成http://localhost:8080

modole

由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。

为了解决以上问题,Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割:

首先在src目录创建store目录,再创建Index.js文件

//引入vue
import Vue from ‘vue’
import Vuex from ‘vuex’
//引入拆分的模块
import user from ‘./modules/userStore.js’
import home from ‘./modules/homeStore.js’
import song from ‘./modules/songStore.js’
//注册vuex
Vue.use(Vuex)
//创建store实例对象
const store = new Vuex.Store({
modules:{
user,
home,
song
}
})
//将模块抛出
export default store

再在main.js文件中引入index.js文件

import store from ‘./store/index.js’

打包(vue)

//执行以下命令
npm run build
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值