0


Vue脚手架学习 vue脚手架配置代理、插槽、Vuex使用、路由、ElementUi插件库的使用

1.vue脚手架配置代理

1.1 方法一

在vue.config.js中添加如下配置:

  1. devServer:{
  2. proxy:"http://localhost:5000"
  3. }

说明:

  1. 优点:配置简单,请求资源时直接发给前端(8080)即可。
  2. 缺点:不能配置多个代理,不能灵活的控制请求是否走代理。如果路径上有8080本身的文件时,就会访问该文件,而不会选择代理。
  3. 工作方式:若按照上述配置代理,当请求了前端不存在的资源时,那么该请求会转发给服务器 (优先匹配前端资源)

1.2 方法二

编写vue.config.js配置具体代理规则:

  1. module.exports = {
  2. devServer: {
  3. proxy: {
  4. '/api1': {// 匹配所有以 '/api1'开头的请求路径
  5. target: 'http://localhost:5000',// 代理目标的基础路径
  6. changeOrigin: true,
  7. pathRewrite: {'^/api1': ''}
  8. },
  9. '/api2': {// 匹配所有以 '/api2'开头的请求路径
  10. target: 'http://localhost:5001',// 代理目标的基础路径
  11. changeOrigin: true,
  12. pathRewrite: {'^/api2': ''}
  13. }
  14. }
  15. }
  16. }
  17. /*
  18. changeOrigin设置为true时,服务器收到的请求头中的host为:localhost:5000
  19. changeOrigin设置为false时,服务器收到的请求头中的host为:localhost:8080
  20. changeOrigin默认值为true
  21. */

说明:

  1. 优点:可以配置多个代理,且可以灵活的控制请求是否走代理。
  2. 缺点:配置略微繁琐,请求资源时必须加前缀。

2.插槽

作用:让父组件可以向子组件指定位置插入html结构,也是一种组件间通信的方式,适用于 父组件 ===> 子组件

分类:默认插槽、具名插槽、作用域插槽

2.1 默认插槽

示例代码:

  1. 父组件中:
  2. <Category>
  3. <div>html结构1</div>
  4. </Category>
  5. 子组件中:
  6. <template>
  7. <div>
  8. <!-- 定义插槽 -->
  9. <slot>插槽默认内容...</slot>
  10. </div>
  11. </template>

2.2 具名插槽

示例代码:

  1. 父组件中:
  2. <Category>
  3. <template slot="center">
  4. <div>html结构1</div>
  5. </template>
  6. <!-- template slot="footer" -->
  7. <template v-slot:footer>
  8. <div>html结构2</div>
  9. </template>
  10. </Category>
  11. 子组件中:
  12. <template>
  13. <div>
  14. <!-- 定义插槽 -->
  15. <slot name="center">插槽默认内容...</slot>
  16. <slot name="footer">插槽默认内容...</slot>
  17. </div>
  18. </template>

2.3 作用域插槽

理解:数据在组件插槽的自身,但根据数据生成的结构需要组件的使用者来决定。(games数据在Category组件中,但使用数据所遍历出来的结构由App组件决定)

示例代码:

  1. 父组件中:
  2. <Category>
  3. <template scope="scopeData">
  4. <!-- 生成的是ul列表 -->
  5. <ul>
  6. <li v-for="g in scopeData.games" :key="g">{{g}}</li>
  7. </ul>
  8. </template>
  9. </Category>
  10. <Category>
  11. <template slot-scope="scopeData">
  12. <!-- 生成的是h4标题 -->
  13. <h4 v-for="g in scopeData.games" :key="g">{{g}}</h4>
  14. </template>
  15. </Category>
  16. 子组件中:
  17. <template>
  18. <div>
  19. <slot :games="games"></slot>
  20. </div>
  21. </template>
  22. <script>
  23. export default {
  24. name:'Category',
  25. props:['title'],
  26. //数据在子组件自身
  27. data() {
  28. return {
  29. games:['红色警戒','穿越火线','劲舞团','超级玛丽']
  30. }
  31. },
  32. }
  33. </script>

3.Vuex

3.1 概念

在Vue中实现集中式状态(数据)管理的一个Vue插件,对vue应用中多个组件的共享状态进行集中式的管理(读/写),也是一种组件间通信的方式,且适用于任意组件间通信。

Vue2必须下载Vuex3,下载 npm i vuex@3

3.2 何时使用?

多个组件需要共享数据时

3.3 搭建vuex环境

  1. 创建文件:src/store/index.js``````//引入Vue核心库import Vue from 'vue'//引入Vueximport Vuex from 'vuex'//应用Vuex插件Vue.use(Vuex)​//准备actions对象——响应组件中用户的动作const actions = {}//准备mutations对象——修改state中的数据const mutations = {}//准备state对象——保存具体的数据const state = {}​//创建并暴露storeexport default new Vuex.Store({ actions, mutations, state})
  2. main.js中创建vm时传入store配置项......//引入storeimport store from './store'......​//创建vmnew Vue({ el:'#app', render: h => h(App), store})

3.4 基本使用

  1. 初始化数据、配置actions、配置mutations,操作文件store.js``````//引入Vue核心库import Vue from 'vue'//引入Vueximport Vuex from 'vuex'//引用VuexVue.use(Vuex)​const actions = { //响应组件中加的动作 jia(context,value){ // console.log('actions中的jia被调用了',miniStore,value) context.commit('JIA',value) },}​const mutations = { //执行加 JIA(state,value){ // console.log('mutations中的JIA被调用了',state,value) state.sum += value }}​//初始化数据const state = { sum:0}​//注意要创建并暴露storeexport default new Vuex.Store({ actions, mutations, state,})
  2. 组件中读取vuex中的数据:$store.state.sum

3.5 getters的使用

  1. 概念:当state中的数据需要经过加工后再使用时,可以使用getters加工。虽然计算属性也可以实现,但是这种方法可以多个组件进行调用。
  2. store.js中追加getters配置
  3. 组件中读取数据:$store.getters.bigSum

代码演示:

  1. ......
  2. const getters = {
  3. bigSum(state){
  4. return state.sum * 10
  5. }
  6. }
  7. //创建并暴露store
  8. export default new Vuex.Store({
  9. ......
  10. getters
  11. })

3.6 四个map方法的使用

3.6.1 mapState方法

用于帮助我们映射

  1. state

中的数据为计算属性,本来要在模版 {{ $store.state.subject }},写成计算属性只需 {{ subject }}, 看起来更简洁

  1. computed: {
  2. //借助mapState生成计算属性:sum、school、subject(对象写法)
  3. ...mapState({sum:'sum',school:'school',subject:'subject'}),
  4. //借助mapState生成计算属性:sum、school、subject(数组写法)
  5. ...mapState(['sum','school','subject']),
  6. },

注意事项:

问题:为什么mapState前面需要用到(...)扩展运算符

原因:

**

  1. mapState

返回一个对象**:

  1. mapState({sum:'sum',school:'school',subject:'subject'})

会返回一个对象,这个对象的键是

  1. sum

  1. school

  1. subject

,值是从 Vuex store 中对应的状态。加上扩展运算符可以将对象的键和值加到computed身上。。

3.6.2 mapGetters方法

用于帮助我们映射

  1. getters

中的数据为计算属性,本来要在模版 {{ $store.getters.bigSum }},写成计算属性只需 {{ bigSum }}, 看起来更简洁

  1. computed: {
  2. //借助mapGetters生成计算属性:bigSum(对象写法)
  3. ...mapGetters({bigSum:'bigSum'}),
  4. //借助mapGetters生成计算属性:bigSum(数组写法)
  5. ...mapGetters(['bigSum'])
  6. },

3.6.3 mapActions方法

用于帮助我们生成与

  1. actions

对话的方法,即:包含

  1. $store.dispatch(xxx)

的函数

  1. methods:{
  2. //靠mapActions生成:incrementOdd、incrementWait(对象形式)
  3. ...mapActions({incrementOdd:'jiaOdd',incrementWait:'jiaWait'})
  4. //靠mapActions生成:incrementOdd、incrementWait(数组形式)
  5. ...mapActions(['jiaOdd','jiaWait'])
  6. }

本来需要这样写

  1. incrementOdd(){
  2. this.$store.dispatch('odd',this.n)
  3. },

简化后

  1. ...mapActions({incrementOdd : 'odd'}),

注意事项:

有参数必须在调用的时候传,不然收到的会是一个事件对象。。

3.6.4 mapMutations方法

用于帮助我们生成与

  1. mutations

对话的方法,即:包含

  1. $store.commit(xxx)

的函数

  1. methods:{
  2. //靠mapActions生成:increment、decrement(对象形式)
  3. ...mapMutations({increment:'JIA',decrement:'JIAN'}),
  4. //靠mapMutations生成:JIA、JIAN(对象形式)
  5. ...mapMutations(['JIA','JIAN']),
  6. }

注意事项:mapActions与mapMutations使用时,若需要传递参数需要:在模板中绑定事件时传递好参数,否则参数是事件对象。

3.7 模块化+命名空间

1.目的:让代码更好维护,让多种数据分类更加明确。

2.修改:

  1. store.js
  1. const countAbout = {
  2. namespaced:true,//开启命名空间
  3. state:{x:1},
  4. mutations: { ... },
  5. actions: { ... },
  6. getters: {
  7. bigSum(state){
  8. return state.sum * 10
  9. }
  10. }
  11. }
  12. const personAbout = {
  13. namespaced:true,//开启命名空间
  14. state:{ ... },
  15. mutations: { ... },
  16. actions: { ... }
  17. }
  18. const store = new Vuex.Store({
  19. modules: {
  20. countAbout,
  21. personAbout
  22. }
  23. })

3.开启命名空间后,组件中读取state数据:

  1. //方式一:自己直接读取
  2. this.$store.state.personAbout.list
  3. //方式二:借助mapState读取:
  4. ...mapState('countAbout',['sum','school','subject']),

4.开启命名空间后,组件中读取getters数据:

  1. //方式一:自己直接读取
  2. this.$store.getters['personAbout/firstPersonName']
  3. //方式二:借助mapGetters读取:
  4. ...mapGetters('countAbout',['bigSum'])

5.开启命名空间后,组件中调用dispatch

  1. //方式一:自己直接dispatch
  2. this.$store.dispatch('personAbout/addPersonWang',person)
  3. //方式二:借助mapActions:
  4. ...mapActions('countAbout',{incrementOdd:'jiaOdd',incrementWait:'jiaWait'})

6.开启命名空间后,组件中调用commit

  1. //方式一:自己直接commit
  2. this.$store.commit('personAbout/ADD_PERSON',person)
  3. //方式二:借助mapMutations:
  4. ...mapMutations('countAbout',{increment:'JIA',decrement:'JIAN'}),

注意事项:

引入模块化之后,模版要改进成下面

$store.state.sum

$store.state.countAbout.sum

4.路由

理解: 一个路由(route)就是一组映射关系(key - value),多个路由需要路由器(router)进行管理。

前端路由:key是路径,value是组件。

1.基本使用

  1. 安装vue-router,命令:npm i vue-router@3
  2. 引入VueRouter并且应用插件:Vue.use(VueRouter)
  3. 编写router配置项://引入VueRouterimport VueRouter from 'vue-router'//引入Luyou 组件import About from '../components/About'import Home from '../components/Home'​//创建router实例对象,去管理一组一组的路由规则const router = new VueRouter({ routes:[ { path:'/about', component:About }, { path:'/home', component:Home } ]})​//暴露routerexport default router
  4. 实现切换(active-class可配置高亮样式)<router-link active-class="active" to="/about">About</router-link>
  5. 指定展示位置<router-view></router-view>

2.几个注意点

  1. 路由组件通常存放在pages文件夹,一般组件通常存放在components文件夹。
  2. 通过切换,“隐藏”了的路由组件,默认是被销毁掉的,需要的时候再去挂载。
  3. 每个组件都有自己的$route属性,里面存储着自己的路由信息。
  4. 整个应用只有一个router,可以通过组件的$router属性获取到。

3.多级路由(多级路由)

1.配置路由规则,使用children配置项:

  1. routes:[
  2. {
  3. path:'/about',
  4. component:About,
  5. },
  6. {
  7. path:'/home',
  8. component:Home,
  9. children:[ //通过children配置子级路由
  10. {
  11. path:'news', //此处一定不要写:/news
  12. component:News
  13. },
  14. {
  15. path:'message',//此处一定不要写:/message
  16. component:Message
  17. }
  18. ]
  19. }
  20. ]

2.跳转(要写完整路径):

  1. <router-link to="/home/news">News</router-link>

注意事项:二级路由开始的路径,最好不要用 /

4.路由的query参数

  1. $route.query.id
  2. $route.query.title

1.传递参数

  1. <!-- 跳转并携带query参数,to的字符串写法 -->
  2. <router-link :to="/home/message/detail?id=666&title=你好">跳转</router-link>
  3. <!-- 跳转并携带query参数,to的对象写法 -->
  4. <router-link
  5. :to="{
  6. path:'/home/message/detail',
  7. query:{
  8. id:666,
  9. title:'你好'
  10. }
  11. }"
  12. >跳转</router-link>

2.接收参数:

  1. $route.query.id
  2. $route.query.title

5.命名路由

1.作用:可以简化路由的跳转。

2.如何使用

  • 给路由命名: - { path:'/demo', component:Demo, children:[ { path:'test', component:Test, children:[ { name:'hello' //给路由命名 path:'welcome', component:Hello, } ] } ]}
  • 简化跳转: - <!--简化前,需要写完整的路径 --><router-link to="/demo/test/welcome">跳转</router-link><!--简化后,直接通过名字跳转 --><router-link :to="{name:'hello'}">跳转</router-link><!--简化写法配合传递参数 --><router-link :to="{ name:'hello', query:{ id:666, title:'你好' } }">跳转</router-link>

6.路由的params参数

params携带参数也就是Restful风格的写法

1.配置路由,声明接收params参数

  1. {
  2. path:'/home',
  3. component:Home,
  4. children:[
  5. {
  6. path:'news',
  7. component:News
  8. },
  9. {
  10. component:Message,
  11. children:[
  12. {
  13. name:'xiangqing',
  14. path:'detail/:id/:title', //使用占位符声明接收params参数
  15. component:Detail
  16. }
  17. ]
  18. }
  19. ]
  20. }

2.传递参数:

  1. <!-- 跳转并携带params参数,to的字符串写法 -->
  2. <router-link :to="/home/message/detail/666/你好">跳转</router-link>
  3. <!-- 跳转并携带params参数,to的对象写法 -->
  4. <router-link
  5. :to="{
  6. name:'xiangqing',
  7. params:{
  8. id:666,
  9. title:'你好'
  10. }
  11. }"
  12. >跳转</router-link>

特别注意:

  • 路由携带params参数时,若使用to的对象写法,则不能使用path配置项,必须使用name配置!
  • params配置的参数,需要在路由器中占位

3.接收参数:

  1. $route.params.id
  2. $route.params.title

7.路由的props配置

作用:让路由组件更方便的收到参数

  1. {
  2. name:'xiangqing',
  3. path:'detail/:id',
  4. component:Detail,
  5. //第一种写法:props值为对象,该对象中所有的key-value的组合最终都会通过props传给Detail组件
  6. // props:{a:900}
  7. //第二种写法:props值为布尔值,布尔值为true,则把路由收到的所有params参数通过props传给Detail组件
  8. // props:true
  9. //第三种写法:props值为函数,该函数返回的对象中每一组key-value都会通过props传给Detail组件
  10. props(route){
  11. return {
  12. id:route.query.id,
  13. title:route.query.title
  14. }
  15. }
  16. }

三种写法:

  • 第一种写法:props值为对象,该对象中所有的key-value的组合最终都会通过props传给Detail组件
  • 第二种写法:props值为布尔值,布尔值为true,则把路由收到的所有params参数通过props传给Detail
  • 第三种写法:props值为函数,该函数返回的对象中每一组key-value都会通过props传给Detail组件

注意事项:

1.第一种写法传的数据都是死数据,所以基本不使用

2.第二种写法只适合传 params参数,不能传 query参数

3.第三种写法是一个回调函数,路由器会调用该方法,并且传该组件的 $route 作为参数

8.

  1. <router-link>

的replace属性

1.作用:控制路由跳转时操作浏览器历史记录的模式(也就是后退和前进) ,可以实现无痕浏览

2.浏览器的历史记录有两种写入方式:分别为

  1. push

  1. replace

  1. push

是追加历史记录,

  1. replace

是替换当前记录。路由跳转时候默认为

  1. push

3.如何开启

  1. replace

模式:

  1. <router-link replace .......>News</router-link>

注意事项:replace的完整写法是 :replace="true"

原理:

9.编程式路由导航

1.作用:不借助

  1. <router-link>

实现路由跳转(to),让路由跳转更加灵活

2.具体编码:

  1. //$router的两个API
  2. this.$router.push({
  3. name:'xiangqing',
  4. params:{
  5. id:xxx,
  6. title:xxx
  7. }
  8. })
  9. this.$router.replace({
  10. name:'xiangqing',
  11. params:{
  12. id:xxx,
  13. title:xxx
  14. }
  15. })
  16. this.$router.forward() //页面前进
  17. this.$router.back() //页面后退
  18. this.$router.go(params) //params为2表示前进2步,-2表示后退两步

10.缓存路由组件

1.作用:切换不同的路由,默认之前的路由是会被销毁的。为了让路由组件保持挂载,不被销毁,以下做法可以实现。

2.具体编码:

  1. // include值是组件名,如果没有配置include就默认缓存所有组件
  2. <keep-alive include="News">
  3. <router-view></router-view>
  4. </keep-alive>

3.使用场景

例如在input框输入了一些信息,然后要切到另外一个组件,回来发现之前输入的信息不见了,是因为组件在切换时就会被销毁,此时就可以设置该组件处于活跃状态就不会被销毁。

4.如果想缓存多个路由

  1. <keep-alive :include="['News','Xxx']">

11.两个新的生命周期钩子

  1. 作用:路由组件所独有的两个钩子,用于捕获路由组件的激活状态。
  2. 具体名字:1. activated路由组件被激活时触发。2. deactivated路由组件失活时触发。
  • **activated**:当一个 keep-alive 组件被激活时触发。这个钩子在组件从缓存中恢复时调用,通常用于恢复组件的状态或执行一些需要在组件激活时进行的操作。
  • **deactivated**:当一个 keep-alive 组件失活时触发。这个钩子在组件被缓存时调用,通常用于清理组件的状态或执行一些需要在组件失活时进行的操作。

注意事项:】

拥有这两个生命周期的条件?

该路由组件被keep-alive修饰。

12.路由守卫

  1. 作用:对路由进行权限控制
  2. 分类:全局守卫、独享守卫、组件内守卫
  3. 全局守卫://全局前置守卫:初始化时执行、每次路由切换前执行router.beforeEach((to,from,next)=>{ console.log('beforeEach',to,from) if(to.meta.isAuth){ //判断当前路由是否需要进行权限控制 if(localStorage.getItem('school') === 'atguigu'){ //权限控制的具体规则 next() //放行 }else{ alert('暂无权限查看') // next({name:'guanyu'}) } }else{ next() //放行 }})//全局后置守卫:初始化时执行、每次路由切换后执行router.afterEach((to,from)=>{ console.log('afterEach',to,from) if(to.meta.title){ document.title = to.meta.title //修改网页的title }else{ document.title = 'vue_test' }})// 向外暴露配置好的路由器export default router
  4. 独享守卫: 只有beforeEnter。在配置路由里面写beforeEnter(to,from,next){ console.log('beforeEnter',to,from) if(to.meta.isAuth){ //判断当前路由是否需要进行权限控制 if(localStorage.getItem('school') === 'atguigu'){ next() }else{ alert('暂无权限查看') // next({name:'guanyu'}) } }else{ next() }}
  5. 组件内守卫://进入守卫:通过路由规则,进入该组件时被调用beforeRouteEnter (to, from, next) {},//离开守卫:通过路由规则,离开该组件时被调用beforeRouteLeave (to, from, next) {}

13.路由器的两种工作模式

  1. 对于一个url来说,什么是hash值?—— #及其后面的内容就是hash值。
  2. hash值不会包含在 HTTP 请求中,即:hash值不会带给服务器。
  3. hash模式:1. 地址中永远带着#号,不美观 。2. 若以后将地址通过第三方手机app分享,若app校验严格,则地址会被标记为不合法。3. 兼容性较好。
  4. history模式:1. 地址干净,美观 。2. 兼容性和hash模式相比略差。3. 应用部署上线时需要后端人员支持,解决刷新页面服务端404的问题。

5.ElementUi组件库的使用

ElementUi官网:https://element.eleme.cn/#/zh-CN/component/quickstart

1.首先安装element-ui插件库

  1. npm i element-ui -S

2.引入 Element

2.1 一般引入

在 main.js 中写入以下内容:

  1. import ElementUI from 'element-ui';
  2. import 'element-ui/lib/theme-chalk/index.css';
  3. Vue.use(ElementUI);

注意事项:上面这种引入方式比较暴力,直接把全部的CSS和组件都引入,会导致所占的空间比较大。

改进方法就是按需引入

2.2 按需引入

1.首先,安装 babel-plugin-component:

  1. npm install babel-plugin-component -D

2.然后,将 .babel.config.js 修改为:

  1. module.exports = {
  2. presets: [
  3. '@vue/cli-plugin-babel/preset',
  4. ["@babel/preset-env", { "modules": false }]
  5. ],
  6. plugins: [
  7. [
  8. "component",
  9. {
  10. "libraryName": "element-ui",
  11. "styleLibraryName": "theme-chalk"
  12. }
  13. ]
  14. ]
  15. }

3.接下来,如果你只希望引入部分组件,比如 Button 和 Select,那么需要在 main.js 中写入以下内容:

使用以下组件

main.js引入部分组件,不需要引入CSS,因为自动会引入所需的部分

  1. import { DatePicker, Dropdown, DropdownMenu, DropdownItem } from 'element-ui';
  2. Vue.component(DatePicker.name, DatePicker);
  3. Vue.component(Dropdown.name, Dropdown);
  4. Vue.component(DropdownMenu.name, DropdownMenu);
  5. Vue.component(DropdownItem.name, DropdownItem);

本文转载自: https://blog.csdn.net/2301_77358195/article/details/142859724
版权归原作者 ‍小林同学学JAVA 所有, 如有侵权,请联系我们删除。

“Vue脚手架学习 vue脚手架配置代理、插槽、Vuex使用、路由、ElementUi插件库的使用”的评论:

还没有评论