组件传值-父传子
<body>
<div id='app'>
<fristson @givefather="getson($event)"></fristson>
</div>
<template id="son">
<div>
<button @click="givedad">给爹</button>
</div>
</template>
</body>
<script>
/*
子传父:
首先要知道子组件如何调用父组件的方法:
1. 首先在父组件内,给引用进来的子组件注册一个事件(事件名是自定义)
2. 在子组件的实例化中,可以通过$emit()方法来调用这个事件
子传父的逻辑:
1. $emit()方法的第二个及以后的参数,是用来定义子组件给父组件传递的内容的
2. 父组件如何拿到这些值
(1) 如果父组件里子组件的自定义事件里的方法没有参数, 那么在实例化层父组件直接给自定义事件里的方法添加参数,就可以拿到子组件的值
(2) 如果父组件里子组件的自定义事件里的方法有参数,那么直接传入$event也能够拿到子组件传的值,但通过$event只能传递$emit里要传递的第一个值
*/
const vm = new Vue({
el: '#app',
data: {
},
methods: {
getson(data, params) {
console.log(data);
console.log(params);
// event可以直接获取子元素的事件对象(这里是子元素的click事件)
console.log(event);
}
},
components: {
'fristson': {
template: '#son',
data() {
return {
sondata: '这是儿子给的',
sondata2: 'param是啥啊'
}
},
methods: {
givedad() {
// 第一个参数: 自定义事件名
// 后面的参数: 要传递的参数,可以为具体值,也可以为一个变量
this.$emit('givefather', this.sondata, this.sondata2)
},
},
// 传值同样可以在声明周期中进行
created() {
// this.$emit('givefather', this.sondata, this.sondata2)
}
}
}
})
</script>
结果如下:
ref的使用
<body>
<div id='app'>
<useref ref="thisdomele"></useref>
</div>
<template id="refneed">
<h1 ref="">hahaha</h1>
</template>
</body>
<script>
Vue.component('useref', {
template: '#refneed',
data() {
return {
msg: 'hahaha'
}
},
methods: {
log1() {
console.log(1);
}
}
})
const vm = new Vue({
el: '#app',
data: {
},
methods: {
},
mounted() {
// 注意ref引用时需要加上this.并在结尾加上s
//this.$refs就加上你为dom起的名字
//至于接下来连.是什么,可以打印出来,再从控制台查看
//几个常用的:
//子组件的数据和方法都能获取,$el能获取子组件的元素
console.log(this.$refs.thisdomele);
this.$refs.thisdomele.log1()
this.$refs.thisdomele.msg
this.$refs.thisdomele.$el.style.color = 'red'
}
})
</script>
结果如下