指令
自定义指令
(1) 自定义指令介绍 directives - 对普通 DOM 元素进行底层操作
//注册一个全局自定义指令`v-focus`
Vue.directive(`focus`,{
//当绑定的元素插入到DOM中时
inserted: function (el){
//聚焦元素
el.focus()
}
})
如果想注册局部指令,组件也要接受一个directives
的选项
directives: {
focus: {
//指令的定义
inserted: function (el){
el.focus
}
}
}
(2) 钩子函数
参数 el,binding,vnode,oldvnode
bind,inserted,update,componentUpdated,unbind
blind:只调用一次,指令第一次绑定到元素时调用。这里可以进行一次性的初始化变量
inserted:被绑定插入父节点时调用(仅保证父节点存在,但不一定已被插入文档中)
update:所在组件的VNode更新时调用,但可能发生在其子VNode更新之前。指令的值可能发生了改变,也可能没有
componentUpdate:指令所在组件的VNode及其子VNode全部更新后调用。
unblind:只调用一次,指令与元素解绑时调用
(3) 函数简写
(4) 自定义指令-轮播
*inserted 插入最后一个元素时初始化swiper
单文件组件
“致命缺点”
全局定义 (Global definitions) 强制要求每个 component 中的命名不得重复
字符串模板 (String templates) 缺乏语法高亮,在 HTML 有多行的时候,需要用到丑陋的
不支持 CSS (No CSS support) 意味着当 HTML 和 JavaScript 组件化时,CSS 明显被遗漏
没有构建步骤 (No build step) 限制只能使用 HTML 和 ES5 JavaScript,而不能使用预处理器,如 Pug (formerly Jade) 和 Babel
<style lang="scss">
$width:300px;
ul li{
background:yellow;
width:$width;
}
</style>
//组件引用
import navbar from './mycomponents/Navbar'
import Vue from 'vue'
//注册
Vue.component("navbar",navbar)
反向代理&别名
让proxy通过vue帮你产生一个代理服务器,
然后通过这个代理服务器去请求数据,最后把请求的数据返回给你
module.expports={
lintOnSave:false,//暂时关闭代码格式jiance
//配置反向代理
devServer:{
proxy:{
'/ajax':{
target:'https://m.maoyan.com',
changeOrigin:true
}
}
}
}
nport navbar from '@/mycomponents/Navbar'//配置的别名
import sidebar from '@ymycomponents/Sidebar'
spa&路由引入
import VueRouter from 'vue-router'
Vue.use(VueRouter)//注册路由插件
//配置表
const routes=[{
path:"/film",
component:Films
}]
重定向
{
path:'*',
redirect:'/films'
}
声明式导航
<li>
<router-link to="/films" active-class="kerwinactive">电影<router-link>
</li>
<li>
<router-link to="cinemas" active-class="kerwinactive">影院<router-link>
</li>
<router-link to="/films" custom v-slot="{navigate,isActive}">
<li @click="navigate">电影--{{isActive}}</li>
</router-link>
<router-link to="/cinemas" custom v-slot="{navigate,isActive}">
<li @click="navigate">影院-{{isActive}}</li>
</router-link>
嵌套路由
import Films from ‘@/views/Films’
import Nowplaying from ‘@/views/films/Nowplaying’
import Comingsoon from ‘@/views/films/Comingsoon’
{
path:'/cinemas/search',
component:search
}
编程式导航
router.push('path路径')
router.push({ path: 'path路径' })
router.push({ name: 'routes配置name属性', params: { 属性: 要传递数据 } }) // 传值
/path/要传递数据
获取参数
this.$route.params.属性
router.push({ name: 'routes配置name属性', query: { 属性: 要传递数据 } })
/path?属性=要传递数据
获取参数
this.$route.query.属性
methods:{
handleChangePage(L{
//编程式导航
//location.herf="#/detail"
this.$router.push('/detail')
})
}
router.replace()替换
router.go(n),n为正整数表示前进,负整数后退,0刷新
动态路由
path:'/detail/:id',
component:Detail
命名路由
name:'kerwinDeta1',//命名路由
path:'/detail/:id',
component:Detail
路由模式
const router=new VueRouter({
mode:'history',
routes:[...]
})
当使用history模式时,URL就像正常的url,例如http://yoursite.com/user/id
需要后台配置支持.因为我们的应用是个单页客户端应用,如果后台没有正确的配置,当用户在浏览器直接访问http://oursite.com/user/id就会返回404