组件传值(子传父)
子组件向父组件传值时,需要借用$emit(‘event-name’,param)来实现传值。
event-name:发射的事件名字
param:事件传递的参数
定义一个组件,并发射一个名为count,参数为value的事件:
Vue.component('first',{
templete:"<h1 @click='clicks'>{{value}}</h1>",
data(){
return{
value:6666
}
},
methods:{
clicks(){
$.emit('count',this.value)
}
})
复制代码
定义一个根组件,并定义一个getCount()方法用来接收子组件发射的值,并改变根组件里的message值。
new Vue({
el:'#app',
data:{
message:'今天天气不错'
},
methods:{
getCount(value){
this.message=value
}
}
})
复制代码
HTML中代码如下:
<html>
<div id='app'>
{{message}}
<first @clicks='getCount'></first>
</div>
</html>
复制代码
组件传值验证
通常组件在传值时,props里的值需要标明类型,也可以设置默认值。
props:{
message{
type:String
},
count{
type:[Number,String],
default:111
}
}
复制代码
组件的生命周期
常用八个:
beforeCreate():组件被创建之前调用
created():组件被创建完毕后调用
beforeMount():在内容挂载之前调用
mounted():内容挂载后调用(最经常使用的生命周期函数,经常会在这个生命周期函数里请求数据)
beforeUpdate():组件内容更新之前调用
updated():组件内容更新后调用
beforeDestroy():组件摧毁之前调用
destroyed():组件摧毁之后调用
不常用两个:
activated():组件激活后调用
deactivated():组件未激活调用
插槽
自定义的组件内部不能直接写入文本,需要使用slot将指定内容放到特定位置。
复制代码
V-show的用法
当值为ture时,元素显示,当值为false时,元素会被隐藏。
v-if当值为false时,会删除元素。
自定义指令
v-directive(id,[definition]), 自定义指令分为全局自定义指令和局部自定义指令两种。inserted插入
Vue.directive('bgcolor' , {
inserted(el , data){
el.style.backgroundColor = data.value
}
})
复制代码
元素查找
vue中自带 一种元素查找方法,与js原生的document.getElementById,Jquery的refs。使用方法:在标签里加入ref属性,在Vue里使用$.refs+属性名查找。具体如下:
<div id='app'>
<h1 ref='message'></h1>
</div>
<script>
new Vue({
el:'#app',
data:{
},
mounted:{
this.$refs.message.style.color='red'//改变message的字体颜色
}
})
</script>
复制代码
动画
Vue中需要使用动画的标签需要放在transition之间,且需要v-if条件渲染或v-show条件展示,同时会调用以下12个周期钩子。
before-enter:进入之前
before-appear:展示之前
before-leave:结束之前
after-enter:进入之后
after-leave:结束之后
after-appear: 展示之后
enter:进入
appear:展示
leave:结束
动画效果写在style样式之中。页面在渲染时,transition标签不会被渲染。而transition-grop会被默认渲染为span,通过tag属性可以更改其默认渲染标签。