vue父子组件之间传值
Vue父向子组件传值主要通过属性方式传值,子组件通过props方式接收
以vue开发去哪儿网为例
一、通过axios发送ajax请求获取到json数据
methods: {
//定义getHomeInfo方法
getHomeInfo () {
axios.get('/api/index.json')
.then(this.getHomeInfoSucc)
//获取到数据后执行getHomeInfoSucc方法
},
//定义getHomeInfoSucc方法
getHomeInfoSucc (res) {
console.log(res)
//打印出res数据
}},mounted () {
//挂载后执行getHomeInfo方法
this.getHomeInfo()
}二、传递字符串例子
1、定义data
data () {
return {
city: ''
}
}2、getHomeInfoSucc方法中为city赋值
getHomeInfoSucc (res) {
res = res.data
if (res.ret && res.data) {
const data = res.data
this.city = data.city
}
}3、子组件中接收数据
props: {
city:String
}4、显示city值
在子组件中显示city的位置插入{{this.city}}
三、传递对象或数组的例子
1、定义data
data () {
return {
city: '',
swiperList: []
}
}2、赋值
getHomeInfoSucc (res) {
res = res.data
if (res.ret && res.data) {
const data = res.data
this.city = data.city
this.swiperList = data.swiperList
}
}3、子组件中接收数据
props: {
swiperList:Array
}4、v-for循环swiperList
<< 上一篇
下一篇 >>