两步走:
1.父组件引用 子组件 通过 import 导入 。定义子组件引用的名称
2.父组件在template元素中引用子组件时 绑定属性 属性和 子组件中的 props:[] 数组中的属性对应起来
父组件写法:
<template>
<element>
<br>
<v-header :title="msg" :run="run" :the="this"></v-header>
我是主页
</element>
</template>
<script>
import storage from '../model/storage.js';
import Header from './Header.vue';
console.log(storage);
export default {
name: 'HelloWorld',
data () {
return {
visible: false,
msg: 'hello vue',
list: [],
data: []
}
},
components:{
'v-header':Header
},
methods:{
run(num){
alert("父组件的方法执行了"+num);
}
},
mounted(){
//生命钩子函数 VUE页面刷新就会加载
console.log("mounted method executed");
}
}
</script>
子组件:
<template>
<element>
<div>我是head组件----{{title}}</div>
<button @click="testRun(123)">子调用父组件的方法</button>
</element>
</template>
<script>
export default {
data(){
return{
}
},
props:['title','run','the'],
methods:{
testRun(num){
//通过传过来的this对象 子页面调用父页面的方法
this.the.run(num+"通过methods方法调用");
}
}
}
</script>