父传子 props
<template>
<div>Home
<button @click="getHomeData()">Home请求数据</button>
<ul>
<li v-for="(item,key) in list" :key=key>
{{item.title}}
</li>
</ul>
<!-- 给子组件传值绑定title属性 -->
<v-header :title='title'></v-header>
<v-life v-if="flag"></v-life>
<button @click="flag=!flag">挂载和卸载组件</button>
</div>
</template>
<script>
import Header from './Header.vue'
import Life from './Life.vue'
import Axios from 'axios'
export default {
data () {
return {
msg: 'home',
flag: true,
list: [],
title: '父组件要传给子组件的值'
}
},
components: {
'v-header': Header,
'v-life': Life
},
methods: {
getHomeData () {
// 请求数据
var api = 'http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1'
Axios.get(api).then((response) => {
this.list = response.data.result
}).catch((error) => {
console.log(error)
})
}
}
}
</script>
<style lang="css" scope>
</style>
<template>
<div>
<h2>头部组件--{{msg}}--{{title}}</h2>
</div>
</template>
<script>
export default {
data () {
return {
msg: '子组件自身属性'
}
},
methods: {
},
// 接受父组件传过来的值
props: ['title']
}
</script>
<style>
</style>
父组件也可以给子组件传递方法或者自身,同时,子组件执行父组件的方法,通过传参,实现子组件给父组件传值
<template>
<div>Home
<button @click="getHomeData()">Home请求数据</button>
<ul>
<li v-for="(item,key) in list" :key=key>
{{item.title}}
</li>
</ul>
<!-- 给子组件传值绑定title属性 -->
<v-header :title='title' :run="run" :home="this"></v-header>
<v-life v-if="flag"></v-life>
<button @click="flag=!flag">挂载和卸载组件</button>
</div>
</template>
<script>
import Header from './Header.vue'
import Life from './Life.vue'
import Axios from 'axios'
export default {
data () {
return {
msg: 'home',
flag: true,
list: [],
title: '父组件要传给子组件的值'
}
},
components: {
'v-header': Header,
'v-life': Life
},
methods: {
getHomeData () {
// 请求数据
var api = 'http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1'
Axios.get(api).then((response) => {
this.list = response.data.result
}).catch((error) => {
console.log(error)
})
},
run (data) {
// 子组件通过执行run方法传递过来的值
console.log(data)
alert('我是父组件的run方法')
}
}
}
</script>
<style lang="css" scope>
</style>
<template>
<div>
<h2>头部组件--{{msg}}--{{title}}</h2>
<button @click="run(123)">子组件执行父组件的run方法</button>
<!-- 通过传参,实现子组件给父组件传值 -->
<button @click="getParent(123)">获取父组件的属性和方法</button>
</div>
</template>
<script>
export default {
data () {
return {
msg: '子组件自身属性'
}
},
methods: {
getParent () {
alert(this.title)
console.log(this.home.title)
}
},
// 接受父组件传过来的值
props: ['title', 'run', 'home']
}
</script>
<style>
</style>