VUE
day01
Vue概述、MVVM模式
vue安装
script引入vue.js文件
vue-cli 命令行安装
script引入步骤
01 先引入script标签
new Vue({ el: '#app', data: { num:1 } })
创建视图标签 <div id="app"></div>
插值表达式 {{ expression }}
指令
选择指令
v-if="expression"
v-else-if="expression"
v-else
循环指令
v-for="(tmp,index) in arr" :key="index"
事件绑定
v-on:event="handle(1)" @event="handle(1)"
new Vue({ methods: { handle(num){ } } })
属性绑定
v-bind:src="expression" :src="expression"
双向数据绑定
v-model="数据"
只能在表单中使用
其它指令
v-text="数据"
在渲染时候,会把之前数据清空 会把html标签解析成普通的文本
v-html="数据"
作用类似于v-text,区别会把html 标签解析成正常标签
v-show="bool"
如果是true,正常显示 否则false,添加一个display:none
组件
概述:html标签的扩展 封装一组html标签
使用步骤
①创建
全局: Vue.component('my-com', { template: `<div>一组标签</div>` })
局部: new Vue({ components: { 'my-com': { template: `<div>一组标签</div>` } } })
②调用
<my-com></my-com>
day02
自定义指令
① 创建
Vue.directive('change', { bind: function(el,bindings){ //el 就是dom元素 // bindings.value 传递的参数 }, inserted: function (el,bindings) { //当前的标签插入到父标签 } })
new Vue({ directives: { 'change': { bind:function(el,bindings){ } } } })
② 调用
<h1 v-change="'red'"></h1>
过滤器
概述:用于对数据进行筛选等操作
使用步骤
① 创建
Vue.filter('myfilter', function(myInput, isBool){ if(isBool){ return myInput.toLowerCase(); } })
new Vue({ filters: { 'myfilter': function(myInput,isBool){} } })
② 调用
<h2>{{msg | myfilter(true)}}</h2>
生命周期函数
beforeCreate / created data数据初始化之前/之后
boforeMount/mounted 渲染的结果挂载之前/之后
beforeUpdate/updated 数据更新之前之/后
beforeDestroy/destroyed (组件、vue实例)销毁前/销毁后
watch 和 computed
watch 侦听器
用于监听数据的变化
在双向数据绑定中使用
new Vue({ watch: { msg: function(newVal, oldVal){ } } })
computed 计算属性
用于处理一些复杂的业务逻辑
有缓存机制,在调用的时候, 如果数据没有变化,就用之前的数据
new Vue({ computed: { mycomputed: function(){ } } })
day03
父组件向子组件通信
① 发送<son mytitle="123"></son>
② 接收 Vue.component('son',{ template: '<h1>{{mytitle}}</h1>', props:['mytitle'] })
子组件向父组件通信
① 在父组件中创建自定义事件
<son @customEvent="rcvMsg"></son> methods:{ rcvMsg: function(msg) { //msg就是传递的参数 } }
② 在子组件中触发父组件的自定义事件
点击触发--- this.$emit('customEvent','hello')
父组件直接获取子组件数据
① 指定子组件的 ref 值
<son ref="myson"></son>
② 在父组件 this.$refs.myson.msg
子组件直接获取父组件数据
this.$parent.msg
兄弟组件之间的通信
步骤
① 创建总线
var bus = new Vue();
② 接收方-创建自定义事件,相当于父组件
在mounted 创建 bus.$on( 'customeEvent', (msg)=>{ } )
③ 发送方-触发接收方事件,当做子组件进行理解就秒懂了
bus.$emit('customEvent','hello')
day04
概述:
建立路径和组件之间的映射关系
使用步骤
① 引入vue-router.js文件
② 创建组件
③ 创建路由实例
var myrouter = new VueRouter({ //配置 })
④ 配置路由
routes: [ {path: '/', redirect: '/login'} {path: '/login', component: Login}, {path: '*', component: page404} ]
⑤ 把路由注册Vue实例
new Vue({ router : myrouter })
⑥ 设置路由切换标签
<router-view></router-view>
路由跳转
<router-link to="/login">登录</router-link>
this.$router.push('/login')
路由传参
① 传递
/login/2
② 接收
路由配置 {path: '/login/:lid'}
this.$route.params.lid
路由嵌套
{path: '/login', component: Login, children: [ {path: '/person', component: Person} ] }
在Login中,添加 <router-view></router-view>