vue使用之slot插槽、router路由和过度动画animate
vue使用之slot插槽、动态组件、router路由和过渡动画animate
1 slot插槽
当组件中某一项需要单独定义,那么就应该使用solt
1.1 单个slot
除非子组件模板包含至少一个
<slot>
插口,否则父组件的内容将会被丢弃 ,当子组件模板只有一个没有属性的 slot 时,父组件整个内容片段将插入到 slot 所在的 DOM 位置,并替换掉 slot 标签本身。
在组件的模版中定义slot
插槽
Vue.component("modal", {
template: `
<div class="modal">
<p>温馨提示</p>
<div>
<slot></slot>
</div>
<button>关闭</button>
</div>
`,
});
1.2 具名插槽
如果一个组件中想使用多个slot那么此时就应该使用具名slot。
Vue.component("modal", {
template: `
<div class="modal">
<slot name="header"></slot>
<slot name="content"></slot>
<slot name="footer"></slot>
</div>
`,
});
<modal>
<p slot="header">温馨提示</p>
<div slot="content">你要删除内容吗</div>
<button slot="footer">关闭</button>
</modal>
<modal>
<p slot="header">提示</p>
<div slot="content">你要删除这条记录吗</div>
<button slot="footer">开启</button>
</modal>
2 动态组件 - component
- 作用:渲染一个“元组件”为动态组件。依
is
的值,来决定哪个组件被渲染。
<!-- 动态组件由 vm 实例的属性值 `componentId` 控制 -->
<component :is="componentId"></component>
<script>
// 两个组件:
Vue.component('home', {
template: '<h1>这是 Home 组件</h1>'
})
Vue.component('login', {
template: '<h1>这是 Login 组件</h1>'
})
data: {
componentId: 'home'
}
</script>
3 router路由
3.1 vue-router的使用
- 安装:
npm i -S vue-router
<body>
<div id="app">
<!-- 5. 配置路由的出口 -->
<router-view></router-view>
</div>
<!-- 1. 引入vue和vue-router -->
<script src="vue.js"></script>
<script src="vue-router.js"></script>
<script>
//2. 准备几个组件
const home = Vue.component('home', {
template: `
<div>这是home组件</div>
`
})
const music = Vue.component('music', {
template: `
<div>这是music组件</div>
`
})
const friend = Vue.component('friend', {
template: `
<div>这是friend组件</div>
`
})
//3. 创建路由对象
const router = new VueRouter({
// 配置路由规则 routes
routes: [
// path:路径
// component: 对应的组件
{ path: '/home', component: home },
{ path: '/music', component: music },
{ path: '/friend', component: friend }
]
})
const vm = new Vue({
el: '#app',
data: {
msg: 'hello vue'
},
// 绑定vue实例与路由对象
// 配置当前vue的路由对象
router
})
</script>
- 解释:将
/
重定向到/home
{ path: '/', redirect: '/home' }
3.2 vue-router的编程式使用
- 说明:我们经常需要把某种模式匹配到的所有路由,全都映射到同一个组件,此时,可以通过路由参数来处理
- 语法:
/user/:id
- 使用:当匹配到一个路由时,参数值会被设置到 this.$route.params
- 其他:可以通过
$route.query
获取到 URL 中的查询字符串(queryString) 等
// 链接:
<router-link to="/user/1001">用户 Jack</router-link>
<router-link to="/user/1002">用户 Rose</router-link>
// 路由:
{ path: '/user/:id', component: User }
// User组件:
const User = {
template: `<div>User {{ $route.params.id }}</div>`
}
4 过渡动画animate
- 安装
npm i animate.css
- 引入
<link rel="stylesheet" href="./node_modules/animate.css/animate.css">
- 使用
<transition name="slide" enter-active-class="animated bounceInLeft"
leave-active-class="animated bounceOutRight">
<p v-show="isShow">{{msg}}</p>
</transition>