自定义指令
私有自定义指令
与data平级定义directives
directives: {
// color: {
// bind(el, obj) {
// el.style.color = obj.value
// }
// },
// color: {
// update(el, obj) {
// el.style.color = obj.value
// }
// },
color(el, obj) {
el.style.color = obj.value
}
}
全局自定义指令
在main.js中new Vue前定义自定义指令
// Vue.directive('color', {
// // 当页面首次被渲染就会执行bind函数
// // el就是绑定的DOM元素
// bind(el, obj) {
// el.style.color = obj.value
// },
// // 当组件重新渲染时会执行
// update(el, obj) {
// console.log('update');
// el.style.color = obj.value
// },
// })
// bind和update业务一样可简写成函数
Vue.directive('color', (el, obj) => {
el.style.color = obj.value
})
使用自定义指令
<template>
<div class="app-container">
<h1 color="textColor">App 根组件</h1>
<button @click="textColor = 'blue'">变</button>
</template>
<script>
export default {
data() {
return {
textColor: 'red'
}
}
}
</script>
路由
前端路由的概念与原理
URL与Hash
URL:用于定位网络上的资源(访问协议://主机名:端口号/存储路径?查询参数#片段)http默认80端口可以不写 https默认443端口可以不写
#后面叫Hash地址,Hash地址发生变化浏览器不会刷新,但会形成历史记录
1.用户点击页面上的路由链接
2.导致Hash地址发生变化
3.前端路由监听到Hash地址的变化
4.把当前Hash地址对应的组件渲染到浏览器中
创建vue-router
安装包 npm i vue-router@3.5.2 -S
在src/router/index。
1.导包
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../component/Home'
import Movie from '../component/Movie'
import About from '../component/About'
2.安装插件
Vue.use(VueRouter )
3.创建实例
const router = new VueRouter({
routes:[
//path 用户访问的 Hash 地址
//component 要展示的组件
//路由重定向redirect
{path:'/' , redirect:"/home"}
{path:'/home' , component:Home},
{path:'/movie' , component:Movie},
//嵌套路由 children
{path:'/about' , component:About,redirect:"/about/xxx" ,children:[
{path:'/about/xxx' ,component:xxxx}
]},
]
})
4.导出
export default router
在main.js中
import router from './router'
new Vue({
render: h => h(App),
//router:router
router
}).$mount('#app')
使用路由
<template>
<div class="app-container">
<h1 v-color="textColor">App 根组件</h1>
//router-link本质就是a链接 to属性会被渲染成href
<router-link to="/home">首页</router-link>
<router-link to="/movie">电影</router-link>
<router-link to="/about">关于</router-link>
//路由占位符
<router-view></router-view>
</div>
</template>
动态路由匹配
在路由规则中 :表示动态参数项
{path:'/home:id' , component:Home}
在组件中获取动态参数项的值可以通过 this.$route.params
简化
{path:'/home:id' , component:Home,props:true}
在组件中获取动态参数项的值可以用 props:['id']
声明式导航
a链接 reout-link
编程式导航
location.href
this.$router.push('Hash地址')
如果在行内调用不需要加this
this.$router.to(数值) 负数是后退 正数是前进










