父组件向子组件传值
<div id="app">
<son :finfo="msg"></son>
</div>
<script>
// 创建 Vue 实例,得到 ViewModel
var vm = new Vue({
el: '#app',
data: {
msg: '这是父组件中的消息'
},
components: {
son: {
template: '<h1>这是子组件 --- {{finfo}}</h1>',
props: ['finfo']
}
}
});
</script>
子组件向父组件传值
<!-- 父组件将方法的引用,传递到子组件内部,子组件在内部调用父组件传递过来的方法,同时把要发送给父组件
的数据,在调用方法的时候当做参数传递过去
-->
<!-- 父组件将方法的引用传递给子组件,其中,getMsg是父组件中methods中定义的方法名称,<func>是子组件调用传递过来方法时候的方法名称</func>-->
<div id="app">
<!-- 引用父组件 -->
<son @func="getMsg"></son>
//组件模板定义
<script type="x-template" id="son">
<div>
<input type="button" value="向父组件传值" @click="sendMsg" />
</div>
</script>
</div>
<script>
//子组件定义方式
Vue.component('son',{
//组件模板id
template:'#son',
methods:{
sendMsg(){
//按钮的点击事件
//调用父组件传递过来的方法,同时把数据传递出去
/* 子组件内部通过this.$emit('方法名', 要传递的数据)方式,来调用父组件中的方法,同时把数据传递给父组件使用 */
this.$emit('func','ok');
}
}
});
//创建Vue实例,得到ViewModel
var vm=new Vue({
el:'#app',
data:{},
methods:{
getMsg(val){
alert(val)
}
}
})
<div id="app">
<div>
<input type="button" value="获取元素内容" @click="getElement" />
<!-- 使用ref获取元素 -->
<h1 ref="myh1">这是一个大大的H1 </h1>
<hr>
<!-- 使用 ref 获取子组件 -->
<my-com ref="mycom"></my-com>
</div>
</div>
<script>
Vue.component('my-com', {
template: '<h5>这是一个子组件</h5>',
data() {
return {
name: '子组件'
}
}
});
// 创建 Vue 实例,得到 ViewModel
var vm = new Vue({
el: '#app',
data: {},
methods: {
getElement() {
// 通过 this.$refs 来获取元素
console.log(this.$refs.myh1.innerText);
// 通过 this.$refs 来获取组件
console.log(this.$refs.mycom.name);
}
}
});
</script>