目录名称

第三章 Vue脚手架

1.配置脚手架

1.1初始化脚手架

  1. Vue 脚手架是 Vue 官方提供的标准化开发工具(开发平台)。

  2. 文档: https://cli.vuejs.org/zh/。

1.2 具体步骤

第一步(仅第一次执行):全局安装@vue/cli。

npm install -g @vue/cli

第二步:切换到你要创建项目的目录,然后使用命令创建项目

vue create xxxx

第三步:启动项目

npm run serve

备注:

如出现下载缓慢请配置 npm 淘宝镜像:npm config set registry https://registry.npm.taobao.org

2.脚手架文件结构

├── node_modules 
├── public
│   ├── favicon.ico: 页签图标
│   └── index.html: 主页面
├── src
│   ├── assets: 存放静态资源
│   │   └── logo.png
│   │── component: 存放组件
│   │   └── HelloWorld.vue
│   │── App.vue: 汇总所有组件
│   │── main.js: 入口文件
├── .gitignore: git版本管制忽略的配置
├── babel.config.js: babel的配置文件
├── package.json: 应用包配置文件 
├── README.md: 应用描述文件
├── package-lock.json:包版本控制文件

3.关于不同版本的Vue

  1. vue.js与vue.runtime.xxx.js的区别:

    1. vue.js是完整版的Vue,包含:核心功能 + 模板解析器。
    2. vue.runtime.xxx.js是运行版的Vue,只包含:核心功能;没有模板解析器。
  2. 因为vue.runtime.xxx.js没有模板解析器,所以不能使用template这个配置项,需要使用render函数接收到的createElement函数去指定具体内容。

  3. main.js

    /* 
       该文件是整个项目的入口文件
    */
    //引入Vue
    import Vue from 'vue'
    //引入App组件,它是所有组件的父组件
    import App from './App.vue'
    //关闭vue的生产提示
    Vue.config.productionTip = false
    //创建Vue实例对象---vm
    new Vue({
       el:'#app',
       //render函数完成了这个功能:将App组件放入容器中
      render: h => h(App),
       // render:q=> q('h1','你好啊')
       // template:`<h1>你好啊</h1>`,
       // components:{App},
    })
    

4.vue.config.js配置文件

  1. 使用vue inspect > output.js可以查看到Vue脚手架的默认配置。
  2. 使用vue.config.js可以对脚手架进行个性化定制,详情见:https://cli.vuejs.org/zh
  3. module.exports = { pages: { index: { //入口 entry: 'src/main.js', }, }, lintOnSave:false, //关闭语法检查
module.exports = {
  pages: {
    index: {
      //入口
      entry: 'src/main.js',
    },
  },
   lintOnSave:false, //关闭语法检查
   //开启代理服务器(方式一)
   /* devServer: {
    proxy: 'http://localhost:5000'
  }, */
   //开启代理服务器(方式二)
   devServer: {
    proxy: {
      '/atguigu': {
        target: 'http://localhost:5000',
            pathRewrite:{'^/bilibili':''},
        // ws: true, //用于支持websocket
        // changeOrigin: true //用于控制请求头中的host值
      },
      '/demo': {
        target: 'http://localhost:5001',
            pathRewrite:{'^/demo':''},
        // ws: true, //用于支持websocket
        // changeOrigin: true //用于控制请求头中的host值
      }
    }
  }
}

5.ref属性

  1. 被用来给元素或子组件注册引用信息(id的替代者)

  2. 应用在html标签上获取的是真实DOM元素,应用在组件标签上是组件实例对象(vc)

  3. 使用方式:

    1. 打标识:<h1 ref="xxx">.....</h1><School ref="xxx"></School>
    2. 获取:this.$refs.xxx
    <template>
     <div>
      <h1 v-text="msg" ref="title"></h1>
      <button ref="btn" @click="showDOM">点我输出上方的DOM元素</button>
      <School ref="sch"/>
     </div>
    </template>
    
    <script>
     //引入School组件
     import School from './components/School'
    
     export default {
      name:'App',
      components:{School},
      data() {
       return {
        msg:'欢迎学习Vue!'
       }
      },
      methods: {
       showDOM(){
        console.log(this.$refs.title) //真实DOM元素
        console.log(this.$refs.btn) //真实DOM元素
        console.log(this.$refs.sch) //School组件的实例对象(vc)
       }
      },
     }
    </script>
    

6.props配置项

  1. 功能:让组件接收外部传过来的数据

  2. 传递数据:<Demo name="xxx"/>

  3. 接收数据:

    1. 第一种方式(只接收):props:['name']

    2. 第二种方式(限制类型):props:{name:String}

    3. 第三种方式(限制类型、限制必要性、指定默认值):

      props:{
      	name:{
      	type:String, //类型
      	required:true, //必要性
      	default:'老王' //默认值
      	}
      }
      

    备注:props是只读的,Vue底层会监测你对props的修改,如果进行了修改,就会发出警告,若业务需求确实需要修改,那么请复制props的内容到data中一份,然后去修改data中的数据。

    <template>
    <div>
    <h1>{{msg}}</h1>
    <h2>学生姓名:{{name}}</h2>
    <h2>学生性别:{{mySex}}</h2>
    <h2>学生年龄:{{myAge+1}}</h2>
    <button @click="updateAge">尝试修改收到的年龄</button>
     <button @click="updateSex">尝试修改收到的性别</button>
    </div>
    </template>
    
    <script>
    export default {
    name:'Student',
    data() {
    console.log(this)
    return {
     msg:'我是一个B站的学生',
     myAge:this.age,
         mySex:this.sex
    }
    },
    methods: {
    updateAge(){
     this.myAge++
    },
       updateSex(){
         if(this.mySex=='男'){
           this.mySex='女';
         }
         else{
           this.mySex='男';
         }
       }
    },
    //简单声明接收
    // props:['name','age','sex'] 
    
    //接收的同时对数据进行类型限制
    /* props:{
    name:String,
    age:Number,
    sex:String
    } */
    
    //接收的同时对数据:进行类型限制+默认值的指定+必要性的限制
    props:{
    name:{
     type:String, //name的类型是字符串
     required:true, //name是必要的
    },
    age:{
     type:Number,
     default:99 //默认值
    },
    sex:{
     type:String,
     required:true
    }
    }
    }
    </script>
    
<template>
 <div>
  <Student name="李四" sex="女" :age="18"/>
 </div>
</template>

<script>
 import Student from './components/Student'

 export default {
  name:'App',
  components:{Student}
 }
</script>

7.mixin(混入)

  1. 功能:可以把多个组件共用的配置提取成一个混入对象

  2. 使用方式:

    第一步定义混合:

    mixin.js

    export const mixin1 = {
    	methods: {
    		showName(){
    			alert(this.name)
    		}
    	},
    	mounted() {
    		console.log('你好啊!')
    	},
    }
    export const hunhe2 = {
    	data() {
    		return {
    			x:100,
    			y:200
    		}
    	},
    }
    
    

    第二步使用混入:

    局部混入:mixins:['xxx']

    <template>
     <div>
      <h2 @click="showName">学生姓名:{{name}}</h2>
      <h2>学生性别:{{sex}}</h2>
     </div>
    </template>
    
    <script>
     import {mixin1,mixin2} from '../mixin'
    
     export default {
      name:'Student',
      data() {
       return {
        name:'张三',
        sex:'男'
       }
      },
      mixins:[mixin1,mixin2]
     }
    </script>
    

    全局混入:Vue.mixin(xxx) 在main.js中配置

    //引入Vue
    import Vue from 'vue'
    //引入App
    import App from './App.vue'
    import {hunhe,hunhe2} from './mixin'
    //关闭Vue的生产提示
    Vue.config.productionTip = false
    
    Vue.mixin(mixin1)
    Vue.mixin(mixin2)
    
    
    //创建vm
    new Vue({
       el:'#app',
       render: h => h(App)
    })
    

8.插件

  1. 功能:用于增强Vue

  2. 本质:包含install方法的一个对象,install的第一个参数是Vue,第二个以后的参数是插件使用者传递的数据。

  3. 定义插件:

    对象.install = function (Vue, options) {
        // 1. 添加全局过滤器
        Vue.filter(....)
    
        // 2. 添加全局指令
        Vue.directive(....)
    
        // 3. 配置全局混入(合)
        Vue.mixin(....)
    
        // 4. 添加实例方法
        Vue.prototype.$myMethod = function () {...}
        Vue.prototype.$myProperty = xxxx
    }
    

    示例

    export default {
       install(Vue,x,y,z){
          console.log(x,y,z)
          //全局过滤器
          Vue.filter('mySlice',function(value){
             return value.slice(0,4)
          })
    
          //定义全局指令
          Vue.directive('fbind',{
             //指令与元素成功绑定时(一上来)
             bind(element,binding){
                element.value = binding.value
             },
             //指令所在元素被插入页面时
             inserted(element,binding){
                element.focus()
             },
             //指令所在的模板被重新解析时
             update(element,binding){
                element.value = binding.value
             }
          })
    
          //定义混入
          Vue.mixin({
             data() {
                return {
                   x:100,
                   y:200
                }
             },
          })
    
          //给Vue原型上添加一个方法(vm和vc就都能用了)
          Vue.prototype.hello = ()=>{alert('你好啊')}
       }
    }
    
  4. 使用插件:Vue.use()

//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'
//引入插件
import plugins from './plugins'
//关闭Vue的生产提示
Vue.config.productionTip = false

//应用(使用)插件
Vue.use(plugins,1,2,3)
//创建vm
new Vue({
   el:'#app',
   render: h => h(App)
})

9.scoped样式

  1. 作用:让样式在局部生效,防止冲突。
  2. 写法:<style scoped>

示例:用在自定义组件中

<template>
 
</template>

<script>

</script>

<style scoped>
 .title{
  color: red;
 }
</style>

10.TodoList案例

10.1案例代码

MyHeader.vue

<template>
  <div class="todo-header">
    <input type="text" placeholder="请输入你的任务名称,按回车键确认" @keyup.enter="add"/>
  </div>
</template>
<script>
import Vue from "vue";
import {nanoid} from "nanoid";
export default Vue.extend({
  name: 'MyHeader',
  props:['addObj'],
  methods: {
    add(event) {
      //console.log(event.target.value);
      const title=event.target.value;
      if(title){
        const todoObj={
          id:nanoid(),title:title,done:false
        };
        this.addObj(todoObj);
        event.target.value="";
      }

    }
  }
})
</script>
<style scoped>
/*header*/
.todo-header input {
  width: 560px;
  height: 28px;
  font-size: 14px;
  border: 1px solid #ccc;
  border-radius: 4px;
  padding: 4px 7px;
}

.todo-header input:focus {
  outline: none;
  border-color: rgba(82, 168, 236, 0.8);
  box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6);
}
</style>

MyList.vue

<template>
  <ul class="todo-main">
    <MyItem v-for="todoObj in todos" :key="todoObj.id" :todo="todoObj" :checkchange="checkchange" :deleteObj="deleteObj">
    </MyItem>

  </ul>
</template>
<script>
import Vue from "vue";
import MyItem from "./MyItem";
export default Vue.extend({
  name:'MyList',
  components:{
    MyItem
  },
  props:['todos','checkchange','deleteObj']

})
</script>
<style scoped>
/*main*/
.todo-main {
  margin-left: 0px;
  border: 1px solid #ddd;
  border-radius: 2px;
  padding: 0px;
}

.todo-empty {
  height: 40px;
  line-height: 40px;
  border: 1px solid #ddd;
  border-radius: 2px;
  padding-left: 5px;
  margin-top: 10px;
}
</style>

MyItem.vue

<template>
  <li>
    <label>
      <input type="checkbox" :checked="todo.done" @change="check(todo.id)"/>
      <span>{{todo.title}}</span>
    </label>
    <button class="btn btn-danger" @click="deleteTodo(todo.id)">删除</button>
  </li>
</template>
<script>
import Vue from "vue";

export default Vue.extend({
  name:'MyItem',
  props:['todo','checkchange','deleteObj'],
  methods:{
    check(id){
      this.checkchange(id);
    },
    deleteTodo(id){
      if(confirm("确认删除吗?")) {
        this.deleteObj(id);
      }
    }
  }

})
</script>
<style scoped>
/*item*/
li {
  list-style: none;
  height: 36px;
  line-height: 36px;
  padding: 0 5px;
  border-bottom: 1px solid #ddd;
}

li label {
  float: left;
  cursor: pointer;
}

li label li input {
  vertical-align: middle;
  margin-right: 6px;
  position: relative;
  top: -1px;
}

li button {
  float: right;
  display: none;
  margin-top: 3px;
}

li:before {
  content: initial;
}

li:last-child {
  border-bottom: none;
}
li:hover{
  background-color: #d0e9c6;
}
li:hover button{
display: block;
}
</style>

MyFooter.vue

<template>
  <div class="todo-footer" v-show="total">
    <label>
<!--      <input type="checkbox" :checked="isAll" @change="selectAll"/>-->
      <input type="checkbox" v-model="isAll"/>
    </label>
    <span>
          <span>已完成{{finished}}</span> / 全部{{total}}
        </span>
    <button class="btn btn-danger" @click="clearTask">清除已完成任务</button>
  </div>
</template>
<script>
import Vue from "vue";

export default Vue.extend({
  name:'MyFooter',
  computed:{
    total(){
          return this.todos.length;
    },
    finished(){
     /* return this.todos.filter(todoObj=>{
        return todoObj.done===true;
      }).length;*/
      return this.todos.reduce((pre,current)=>pre+(current.done?1:0),0);
    },
    isAll:{
      get() {
        return this.finished === this.total;
      },
      set(value){
        this.checkAllTodo(value);
      }
    }
  },
  props:['todos','clearFinished','checkAllTodo'],
  methods:{
    /*selectAll(e){
      this.checkAllTodo(e.target.checked);
    },*/
    clearTask(){
      if(confirm('确定删除已完成任务?')) {
        this.clearFinished(this.todos.filter(todoObj => {
          return todoObj.done != true;
        }));
      }
    }
  }
})
</script>
<style scoped>
/*footer*/
.todo-footer {
  height: 40px;
  line-height: 40px;
  padding-left: 6px;
  margin-top: 5px;
}

.todo-footer label {
  display: inline-block;
  margin-right: 20px;
  cursor: pointer;
}

.todo-footer label input {
  position: relative;
  top: -1px;
  vertical-align: middle;
  margin-right: 5px;
}

.todo-footer button {
  float: right;
  margin-top: 5px;
}
</style>

App.vue

<template>
  <div id="root">
    <div class="todo-container">
      <div class="todo-wrap">
       <MyHeader :addObj="addObj"></MyHeader>
        <MyList :todos="todos" :checkchange="checkchange" :deleteObj="deleteObj"></MyList>
       <MyFooter :todos="todos" :clearFinished="clearFinished" :checkAllTodo="checkAllTodo"></MyFooter>
      </div>
    </div>
  </div>

</template>
<script>
import Vue from "vue";
import MyHeader from "./components/MyHeader";
import MyList from "./components/MyList";
import MyFooter from "./components/MyFooter";
export default Vue.extend({
  name:'App',
  data(){
    return {
      todos:localStorage.getItem("todos")||[]
    }
  },
  methods:{
    addObj(todoObj){
      this.todos.unshift(todoObj);
    },
    checkchange(id){
     this.todos.forEach((todoObj)=>{
        if(todoObj.id===id){
          todoObj.done=!todoObj.done;
        }
      });
    },
    deleteObj(id){this.todos=this.todos.filter(todoObj=>{
        return todoObj.id!==id;
      });
    },
    checkAllTodo(flag){
this.todos.filter(todo=>todo.done=flag)
    },
    clearFinished(todos) {
      this.todos=todos;
    }
  },
  components:{


    MyHeader,

    MyList,
    MyFooter
  },
  watch:{
    todos:{
      deep:true,
      handler(value){
        localStorage.setItem("todos",JSON.stringify(value))
      }
    }
  }

})
</script>
<style>
/*base*/
body {
  background: #fff;
}

.btn {
  display: inline-block;
  padding: 4px 12px;
  margin-bottom: 0;
  font-size: 14px;
  line-height: 20px;
  text-align: center;
  vertical-align: middle;
  cursor: pointer;
  box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05);
  border-radius: 4px;
}

.btn-danger {
  color: #fff;
  background-color: #da4f49;
  border: 1px solid #bd362f;
}

.btn-danger:hover {
  color: #fff;
  background-color: #bd362f;
}

.btn:focus {
  outline: none;
}

.todo-container {
  width: 600px;
  margin: 0 auto;
}
.todo-container .todo-wrap {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
}








</style>

10.2 总结TodoList案例

  1. 组件化编码流程:

    (1).拆分静态组件:组件要按照功能点拆分,命名不要与html元素冲突。

    (2).实现动态组件:考虑好数据的存放位置,数据是一个组件在用,还是一些组件在用:

    1).一个组件在用:放在组件自身即可。

    2). 一些组件在用:放在他们共同的父组件上(状态提升)。

    (3).实现交互:从绑定事件开始。

  2. props适用于:

    (1).父组件 ==> 子组件 通信

    (2).子组件 ==> 父组件 通信(要求父先给子一个函数)

  3. 使用v-model时要切记:v-model绑定的值不能是props传过来的值,因为props是不可以修改的!

  4. props传过来的若是对象类型的值,修改对象中的属性时Vue不会报错,但不推荐这样做。

11.webStorage

11.1 webStorage 代码示例

<!DOCTYPE html>
<html>
   <head>
      <meta charset="UTF-8" />
      <title>localStorage</title>
   </head>
   <body>
      <h2>localStorage</h2>
      <button onclick="saveData()">点我保存一个数据</button>
      <button onclick="readData()">点我读取一个数据</button>
      <button onclick="deleteData()">点我删除一个数据</button>
      <button onclick="deleteAllData()">点我清空一个数据</button>

      <script type="text/javascript" >
         let p = {name:'张三',age:18}

         function saveData(){
            localStorage.setItem('msg','hello!!!')
            localStorage.setItem('msg2',666)
            localStorage.setItem('person',JSON.stringify(p))
         }
         function readData(){
            console.log(localStorage.getItem('msg'))
            console.log(localStorage.getItem('msg2'))

            const result = localStorage.getItem('person')
            console.log(JSON.parse(result))

            // console.log(localStorage.getItem('msg3'))
         }
         function deleteData(){
            localStorage.removeItem('msg2')
         }
         function deleteAllData(){
            localStorage.clear()
         }
      </script>
   </body>
</html>

11.2 webStorage总结

  1. 存储内容大小一般支持5MB左右(不同浏览器可能还不一样)

  2. 浏览器端通过 Window.sessionStorage 和 Window.localStorage 属性来实现本地存储机制。

  3. 相关API:

    1. xxxxxStorage.setItem('key', 'value'); 该方法接受一个键和值作为参数,会把键值对添加到存储中,如果键名存在,则更新其对应的值。

    2. xxxxxStorage.getItem('person');

      该方法接受一个键名作为参数,返回键名对应的值。

    3. xxxxxStorage.removeItem('key');

      该方法接受一个键名作为参数,并把该键名从存储中删除。

    4. xxxxxStorage.clear()

      该方***清空存储中的所有数据。

  4. 备注:

    1. SessionStorage存储的内容会随着浏览器窗口关闭而消失。
    2. LocalStorage存储的内容,需要手动清除才会消失。
    3. xxxxxStorage.getItem(xxx)如果xxx对应的value获取不到,那么getItem的返回值是null。
    4. JSON.parse(null)的结果依然是null。

12.组件的自定义事件

12.1 组件自定义事件总结

  1. 一种组件间通信的方式,适用于:子组件 ===> 父组件

  2. 使用场景:A是父组件,B是子组件,B想给A传数据,那么就要在A中给B绑定自定义事件(事件的回调在A中)。

  3. 绑定自定义事件:

    1. 第一种方式,在父组件中:<Demo @atguigu="test"/><Demo v-on:atguigu="test"/>

    2. 第二种方式,在父组件中:

      <Demo ref="demo"/>
      ......
      mounted(){
         this.$refs.xxx.$on('atguigu',this.test)
      }
      
    3. 若想让自定义事件只能触发一次,可以使用once修饰符,或$once方法。

  4. 触发自定义事件:this.$emit('atguigu',数据)

  5. 解绑自定义事件this.$off('atguigu')

  6. 组件上也可以绑定原生DOM事件,需要使用native修饰符。

  7. 注意:通过this.$refs.xxx.$on('atguigu',回调)绑定自定义事件时,回调要么配置在methods中,要么用箭头函数,否则this指向会出问题!

12.2 自定义事件案例

App.vue

<template>
 <div class="app">
  <h1>{{msg}},学生姓名是:{{studentName}}</h1>

  <!-- 通过父组件给子组件传递函数类型的props实现:子给父传递数据 -->
  <School :getSchoolName="getSchoolName"/>

  <!-- 通过父组件给子组件绑定一个自定义事件实现:子给父传递数据(第一种写法,使用@或v-on) -->
  <!-- <Student @bilibili="getStudentName" @demo="m1"/> -->

  <!-- 通过父组件给子组件绑定一个自定义事件实现:子给父传递数据(第二种写法,使用ref) -->
  <Student ref="student" @click.native="show"/>
 </div>
</template>

<script>
 import Student from './components/Student'
 import School from './components/School'

 export default {
  name:'App',
  components:{School,Student},
  data() {
   return {
    msg:'你好啊!',
    studentName:''
   }
  },
  methods: {
   getSchoolName(name){
    console.log('App收到了学校名:',name)
   },
   getStudentName(name,...params){
    console.log('App收到了学生名:',name,params)
    this.studentName = name
   },
   m1(){
    console.log('demo事件被触发了!')
   },
   show(){
    alert(123)
   }
  },
  mounted() {
   this.$refs.student.$on('bilibili',this.getStudentName) //绑定自定义事件
   // this.$refs.student.$once('bilibili',this.getStudentName) //绑定自定义事件(一次性)
  },
 }
</script>

<style scoped>
 .app{
  background-color: gray;
  padding: 5px;
 }
</style>

Student.vue

<template>
 <div class="student">
  <h2>学生姓名:{{name}}</h2>
  <h2>学生性别:{{sex}}</h2>
  <h2>当前求和为:{{number}}</h2>
  <button @click="add">点我number++</button>
  <button @click="sendStudentlName">把学生名给App</button>
  <button @click="unbind">解绑atguigu事件</button>
  <button @click="death">销毁当前Student组件的实例(vc)</button>
 </div>
</template>

<script>
 export default {
  name:'Student',
  data() {
   return {
    name:'张三',
    sex:'男',
    number:0
   }
  },
  methods: {
   add(){
    console.log('add回调被调用了')
    this.number++
   },
   sendStudentlName(){
    //触发Student组件实例身上的atguigu事件
    this.$emit('bilibili',this.name,666,888,900)
    // this.$emit('demo')
    // this.$emit('click')
   },
   unbind(){
    this.$off('bilibili') //解绑一个自定义事件
    // this.$off(['bilibili','demo']) //解绑多个自定义事件
    // this.$off() //解绑所有的自定义事件
   },
   death(){
    this.$destroy() //销毁了当前Student组件的实例,销毁后所有Student实例的自定义事件全都不奏效。
   }
  },
 }
</script>

<style lang="less" scoped>
 .student{
  background-color: pink;
  padding: 5px;
  margin-top: 30px;
 }
</style>

School.vue

<template>
 <div class="school">
  <h2>学校名称:{{name}}</h2>
  <h2>学校地址:{{address}}</h2>
  <button @click="sendSchoolName">把学校名给App</button>
 </div>
</template>

<script>
 export default {
  name:'School',
  props:['getSchoolName'],
  data() {
   return {
    name:'B站',
    address:'北京',
   }
  },
  methods: {
   sendSchoolName(){
    this.getSchoolName(this.name)
   }
  },
 }
</script>

<style scoped>
 .school{
  background-color: skyblue;
  padding: 5px;
 }
</style>

13.全局事件总线(GlobalEventBus)

  1. 一种组件间通信的方式,适用于任意组件间通信。

  2. 安装全局事件总线:

    new Vue({
    	......
    	beforeCreate() {
    		Vue.prototype.$bus = this //安装全局事件总线,$bus就是当前应用的vm
    	},
        ......
    }) 
    
  3. 使用事件总线:

    1. 接收数据:A组件想接收数据,则在A组件中给$bus绑定自定义事件,事件的回调留在A组件自身。

      methods(){
        demo(data){......}
      }
      ......
      mounted() {
        this.$bus.$on('xxxx',this.demo)
      }
      
    2. 提供数据:this.$bus.$emit('xxxx',数据)

  4. 最好在beforeDestroy钩子中,用$off去解绑当前组件所用到的事件(接受数据的一方)。

    beforeDestroy() {
     this.$bus.$off('xxxx')
    },
    

14.消息订阅与发布(pubsub)

  1. 一种组件间通信的方式,适用于任意组件间通信。

  2. 使用步骤:

    1. 安装pubsub:npm i pubsub-js

    2. 引入: import pubsub from 'pubsub-js'

    3. 接收数据:A组件想接收数据,则在A组件中订阅消息,订阅的回调留在A组件自身。

      methods(){
        demo(msgName,data){......}//msgName:消息名称,data:数据 可使用_做占位符(msgName一般用不到)只接受第二个参数demo(_,data){......}
      }
      ......
      mounted() {
        this.pubId = pubsub.subscribe('消息名称',this.demo(回调函数)) //订阅消息
          //注意:第二个参数回调函数要么配置在methods中,要么用箭头函数,否则this指向会出问题!
          this.pubId = pubsub.subscribe('消息名称',(msgName,data)=>{
      				console.log(this)//this指向组件实例对象
      				// console.log('有人发布了hello消息,hello消息的回调执行了',msgName,data)
      			})
      }
      
    4. 提供数据:pubsub.publish('xxx',数据)

    methods: {
     sendStudentName(){
      pubsub.publish('消息名称',数据)
     }
    },
    
    1. 最好在beforeDestroy钩子中,用PubSub.unsubscribe(pid)去取消订阅。
      this.pubId = pubsub.subscribe('消息名称',this.demo(回调函数)) //订阅消息
        //注意:第二个参数回调函数要么配置在methods中,要么用箭头函数,否则this指向会出问题!
        this.pubId = pubsub.subscribe('消息名称',(msgName,data)=>{
    				console.log(this)//this指向组件实例对象
    				// console.log('有人发布了hello消息,hello消息的回调执行了',msgName,data)
    			})
    };
    beforeDestroy() {
     pubsub.unsubscribe(this.pubId)//取消订阅
    },
    

15.nextTick

  1. 语法:this.$nextTick(回调函数)

    this.$nextTick(function(){
     this.$refs.inputTitle.focus()//获取焦点
    })
    
  2. 作用:在下一次 DOM 更新结束后执行其指定的回调。

  3. 什么时候用:当改变数据后,要基于更新后的新DOM进行某些操作时,要在nextTick所指定的回调函数中执行。

16.Vue封装的过度与动画

16.1 基本使用

  1. 作用:在插入、更新或移除 DOM元素时,在合适的时候给元素添加样式类名。

  2. 写法:

    1. 使用<transition>包裹要过度的元素,并配置name属性:

      <transition name="hello">
      	<h1 v-show="isShow">你好啊!</h1>
      </transition>
      
    2. 备注:若有多个元素需要过度,则需要使用:<transition-group>,且每个元素都要指定key值。

    <transition-group >
     <h1 v-show="!isShow" key="1">你好啊!</h1>
     <h1 v-show="isShow" key="2">B站!</h1>
    </transition-group>
    

16.2 引入第三方动画-Animate.css

官网:animate.style

使用方式:

1.使用 npm 安装:

$ npm install animate.css --save

2.将其导入您的文件:

import 'animate.css';

3.基本用法

安装 Animate.css 后,将类animate__animated与任何动画名称一起添加到元素(不要忘记animate__前缀!):

<h1 class="animate__animated animate__bounce">An animated element</h1>
  1. 使用 或标签
<transition-group 
 appear //动画出现效果
 name="animate__animated animate__bounce" //样式前缀
 enter-active-class="animate__swing"//进入动画样式
 leave-active-class="animate__backOutUp"//离开动画样式      
>
 <h1 v-show="!isShow" key="1">你好啊!</h1>
 <h1 v-show="isShow" key="2">B站!</h1>
</transition-group>

17.数据交互

17.1数据请求的方式

1.xhr new XMLHttpRequest() xhr.open() xhr.send() 用的较少

  1. JQuery .get().get() .post xhr封装

  2. axios Vue推荐 xhr封装

  3. fetch

  4. vue-resource(Vue插件 xhr封装 )

    安装: npm npm i vue-resource

    引入: import vueResource from "vue-resource"

    使用插件:Vue.use(vueResource )

    发送请求:this.$http.get()

17.2解决跨域请求

跨域:是指浏览器不能执行其他网站的脚本。它是由浏览器的同源策略造成的,是浏览器对JavaScript实施的安全限制

1.CORS(Cross-Origin Resource Sharing),跨域资源共享

当使用XMLHttpRequest发送请求时,如果浏览器发现违反了同源策略就会自动加上一个请求头 origin;

后端在接受到请求后确定响应后会在 Response Headers 中加入一个属性 Access-Control-Allow-Origin;

浏览器判断响应中的 Access-Control-Allow-Origin 值是否和当前的地址相同,匹配成功后才继续响应处理,否则报错

缺点:忽略 cookie,浏览器版本有一定要求

2.sonp

利用了 script 不受同源策略的限制

缺点:只能 get 方式,易受到 XSS攻击

3.代理服务器

1.nginx

2.vue-cli vue脚手架配置代理

18.vue脚手架配置代理

方法一

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

devServer:{
  proxy:"http://localhost:5000"
}

说明:

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

方法二

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

module.exports = {
	devServer: {
      proxy: {
      '/api1': {// 匹配所有以 '/api1'开头的请求路径
        target: 'http://localhost:5000',// 代理目标的基础路径
        pathRewrite:{'^/api1':''},//重写地址,将前缀替换
          changeOrigin: true,
        pathRewrite: {'^/api1': ''}
      },
      '/api2': {// 匹配所有以 '/api2'开头的请求路径
        target: 'http://localhost:5001',// 代理目标的基础路径
        pathRewrite:{'^/api2':''},//重写地址,将前缀替换
        changeOrigin: true,
        pathRewrite: {'^/api2': ''}
      }
    }
  }
}
/*
   changeOrigin设置为true时,服务器收到的请求头中的host为:localhost:5000
   changeOrigin设置为false时,服务器收到的请求头中的host为:localhost:8080
   changeOrigin默认值为true
*/

说明:

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

19.gitHub搜索案例

效果图:

在这里插入图片描述

Search.vue

<template>
  <div>
    <section class="jumbotron">
      <h3 class="jumbotron-heading">Search Github Users</h3>
      <div>
        <input type="text" placeholder="enter the name you search" v-model="ketword"/>
        &nbsp;<button @click="getUsers">Search</button>
      </div>
    </section>
  </div>
</template>

<script>
import axios from "axios";
import pubsub from "pubsub-js";

export default {
  name: "Search",
  data() {
    return {
      ketword: ''
    }
  },
  methods: {
    getUsers() {
      //全局事件总线
      //this.$bus.$emit("updateDataList", {isFirst: false, isLoading: true, errMsg: "", users: []});
      //消息订阅
      pubsub.publish("updateDataList", {isFirst: false, isLoading: true, errMsg: "", users: []});
      axios.get(`https://api.github.com/search/users?q=${this.ketword}`).then(
          response => {
            console.log("请求成功");
            //全局事件总线
            //this.$bus.$emit("updateDataList", {isLoading: false, errMsg: "".message, users: response.data.items});
            //消息订阅
            pubsub.publish("updateDataList", {isLoading: false, errMsg: "".message, users: response.data.items});
          },
          error => {
            console.log("请求失败")
            //全局事件总线
            //this.$bus.$emit("updateDataList", {isLoading: false, errMsg: error.message, users: []});
            //消息订阅
            pubsub.publish("updateDataList", {isLoading: false, errMsg: error.message, users: []});
          }
      )

    }
  }
}
</script>

<style scoped>

</style>

List.vue

<template>
  <div class="row">
    <!--展示用户列表
    -->
    <div class="card" v-for="(user) in info.users" :key="user.login">
      <a :href="user.html_url" target="_blank">
        <img :src="user.avatar_url" style='width: 100px'/>
      </a>
      <p class="card-text">{{ user.login }}</p>
    </div>
<!--第一次加载欢迎
-->
    <h1 v-show="info.isFirst">欢迎你!</h1>
<!--加载中页面
-->
    <h1 v-show="info.isLoading">加载中。。。。。</h1>
<!--错误页面
-->
    <h1 v-show="info.errMsg">{{info.errMsg}}</h1>


  </div>
</template>

<script>
import pubsub from "pubsub-js";
export default {
  name: "List",
  data() {
    return {
      info:{
        isFirst: true,
        isLoading: false,
        errMsg: "",
        users: []
      }
    }
  },
  mounted() {
    //全局事件总线
   /* this.$bus.$on("updateDataList", (userObj) => {
      this.info = {...this.info,...userObj};//es6 语法 将userObj有的参数替换,没有的保持原样
    });*/
    //消息订阅
    //注意:第二个参数回调函数要么配置在methods中,要么用箭头函数,否则this指向会出问题!
    this.pubId = pubsub.subscribe('updateDataList',(msgName,userObj)=>{
      this.info = {...this.info,...userObj};//es6 语法 将userObj有的参数替换,没有的保持原样
    })
  },
  beforeDestroy() {
    //解绑事件
    //this.$bus.$off("updateDataList");
    //取消订阅
    pubsub.unsubscribe(this.pubId);
  }
}
</script>

<style scoped>
.album {
  min-height: 50rem; /* Can be removed; just added for demo purposes */
  padding-top: 3rem;
  padding-bottom: 3rem;
  background-color: #f7f7f7;
}

.card {
  float: left;
  width: 33.333%;
  padding: .75rem;
  margin-bottom: 2rem;
  border: 1px solid #efefef;
  text-align: center;
}

.card > img {
  margin-bottom: .75rem;
  border-radius: 100px;
}

.card-text {
  font-size: 85%;
}
</style>

App.vue

<template>
  <div class="container">
    <search></search>
    <List></List>
  </div>
</template>

<script>
import Search from "./components/Search";
import List from "./components/List";

export default {
  name: "app",
  components: {List, Search},
}
</script>

<style>
</style>

main.js

//引入Vue
import Vue from 'vue'
//引入App
import App from './App'
//关闭Vue的生产提示
Vue.config.productionTip = false

//创建vm
new Vue({
   el:'#app',
   render: h => h(App),
   beforeCreate() {
      Vue.prototype.$bus=this;
   }
})

index.html

<!DOCTYPE html>
<html lang="">
  <head>
    <meta charset="utf-8">
      <!-- 针对IE浏览器的一个特殊配置,含义是让IE浏览器以最高的渲染级别渲染页面 -->
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <!-- 开启移动端的理想视口 -->
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
      <!-- 配置页签图标 -->
    <link rel="icon" href="<%= BASE_URL %>favicon.ico">
      <!-- 引入第三方样式 -->
      <link rel="stylesheet" href="<%= BASE_URL %>css/bootstrap.css">
      <!-- 配置网页标题 -->
    <title>硅谷系统</title>
  </head>
  <body>
      <!-- 当浏览器不支持js时noscript中的元素就会被渲染 -->
    <noscript>
      <strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
    </noscript>
      <!-- 容器 -->
    <div id="app"></div>
    <!-- built files will be auto injected -->
  </body>
</html>

20.插槽

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

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

  3. 使用方式:

    1. 默认插槽:

      父组件中:
              <Category>
                 <div>html结构1</div>
              </Category>
      子组件中:
              <template>
                  <div>
                     <!-- 定义插槽 -->
                     <slot>插槽默认内容...</slot>
                  </div>
              </template>
      
    2. 具名插槽:

      父组件中:
              <Category>
                  <template slot="center">
                    <div>html结构1</div>
                  </template>
      
                  <template v-slot:footer>
                     <div>html结构2</div>
                  </template>
              </Category>
      子组件中:
              <template>
                  <div>
                     <!-- 定义插槽 -->
                     <slot name="center">插槽默认内容...</slot>
                     <slot name="footer">插槽默认内容...</slot>
                  </div>
              </template>
      
    3. 作用域插槽:

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

      2. 具体编码:

        父组件中:
        		<Category>
        			<template scope="scopeData">
        				<!-- 生成的是ul列表 -->
        				<ul>
        					<li v-for="g in scopeData.games" :key="g">{{g}}</li>
        				</ul>
        			</template>
        		</Category>
                  <Category title="游戏">
        			<template scope="{games}">
        				<ol>
                            <li style="color:red" v-for="(g,index) in games" :key="index">{{g}}</li>                  </ol>
        			</template>
        		</Category>
        		<Category>
        			<template slot-scope="scopeData">
        				<!-- 生成的是h4标题 -->
        				<h4 v-for="g in scopeData.games" :key="g">{{g}}</h4>
        			</template>
        		</Category>
        子组件中:
                <template>
                    <div>
                        <slot :games="games"></slot>
                    </div>
                </template>
        		
                <script>
                    export default {
                        name:'Category',
                        props:['title'],
                        //数据在子组件自身
                        data() {
                            return {
                                games:['红色警戒','穿越火线','劲舞团','超级玛丽']
                            }
                        },
                    }
                </script>