vue组件数据传递:
1.父组件传递给子组件:在父组件引用的子组件标签上增加属性就可以传递,子组件在props: {父子间属性名称:数据类型}中接收
2.子组件监听父组件方法 ,使用this.$emit()触发父组件属性
代码示例:
父组件:
主要看<city-alphabet>子组件标签内容,
:cities='' cities''为传递cities数据给子组件,
@change="handleLetterChange"为子组件监听的属性触发 handleLetterChange()方法
<template>
<div>
<city-header></city-header>
<city-search></city-search>
<city-list
:hot="hotCities"
:cities="cities"
:letter="letter"
></city-list>
<city-alphabet
:cities="cities"
@change="handleLetterChange"
></city-alphabet>
</div>
</template>
<script>
import CityHeader from './components/Header'
import CitySearch from './components/Search'
import CityList from './components/List'
import CityAlphabet from './components/Alphabet'
import axios from 'axios'
export default {
name: 'city',
components: {
CityHeader,
CitySearch,
CityList,
CityAlphabet
},
data() {
return {
hotCities: [],
cities: {},
letter: ''
}
},
mounted() {
this.getCityInfo()
},
methods: {
getCityInfo() {
axios.get('/api/city.json')
.then(this.getCityInfoSucc)
},
getCityInfoSucc(res) {
res = res.data
if (res.ret && res.data) {
const data = res.data
this.hotCities = data.hotCities
this.cities = data.cities
}
},
handleLetterChange(letter) {
this.letter = letter
}
}
}
</script>
<style scoped>
</style>
子组件:
对应父组件<city-alphabet>标签
this.$emit('change', this.letters[index])为监听父组件change,并传参数
<template>
<ul class="list">
<li
class="item"
v-for="item of letters"
:key="item"
:ref="item"
@touchstart="handleTouchStart"
@touchmove="handleTouchMove"
@touchend="handleTouchEnd"
@click="handleLetterClick"
>{{item}}</li>
</ul>
</template>
<script>
export default {
name: "CityAlphabet",
props: {
cities: Object
},
computed: {
letters() {
const letters = []
for (let i in this.cities) {
letters.push(i)
}
return letters
}
},
data() {
return {
touchStatus: false
}
},
methods: {
handleLetterClick(e) {
this.$emit('change', e.target.innerText)
},
// handleTouch...系列方法是 手指在手机屏幕的右侧字母滑动时,左侧城市列表跟着变化,可以不增加此功能,只有点击字母表城市列表变化也很合理
handleTouchStart() {
this.touchStatus = true
},
handleTouchMove(e) {
if (this.touchStatus) {
// A字母到input框的距离
const startY = this.$refs['A'][0].offsetTop
//手指位置到input的距离 = 手指位置距离顶部位置 - header
const touchY = e.touches[0].clientY - 79
// 当前手指的字母位置
const index = Math.floor((touchY - startY) / 20)
if (index >= 0 && index < this.letters.length) {
this.$emit('change', this.letters[index])
}
}
},
handleTouchEnd() {
this.touchStatus = false
}
}
}
</script>
<style lang="stylus" scoped>
@import '~styles/varibless.styl'
.list
display flex
flex-direction column
justify-content center
position absolute
right 0
top 1.58rem
bottom 0
width .4rem
.item
line-height .4rem
text-align center
color $bgColor
</style>