前段时间做了一个小样,用到了数据通信,因为只是小样,所以就不考虑vuex了,为了加深印象,简单的做个小结。
三个按钮是一个组件,点击按钮时,能改变父组件的状态,显示不同的数据,并且实时更新按钮的选中状态
首先一个,vue2.0只支持单项传递数据,在子组件中我们不能直接去改动父组件的数据,那么我们可以去通知父组件,要改动哪个数据,然后让父组件去改
所以,下面我们就用到了
$emit
,在子组件中通过$emit
去触发父元素的自定义事件,并把要改的值传给父元素,然后父元素就可以去监听一个事件,去改动这个值父组件部分代码:
父组件通过绑定数据 :desc="desc" :ratings="ratings" :select-type="selectType" :only-content="onlyContent"将数据传递给子组件,select="ratingtype_select"跟toggle="ratingtype_toggle"是自定义事件,当子组件通过
$emit
触发这个事件的时候,就会去执行这个事件所绑定的函数,ratingtype_select函数有一个参数,传进来的参数就是子组件的$emit
所传过来的数据,改变选中的按钮状态之后通过needShow函数去改变父元素的评论信息部分
<v-ratingselect
:desc="desc"
:ratings="ratings"
:select-type="selectType"
:only-content="onlyContent"
@select="ratingtype_select"
@toggle="ratingtype_toggle"
>
</v-ratingselect>
....
<div class="rating-wrapper">
<ul>
<li class="rating-item border-1px" v-for="rating in ratings" :key="rating.id" v-show="needShow(rating.rateType, rating.text)">
</ul>
</div>
methods: {
ratingtype_select(type) {
this.selectType = type
},
ratingtype_toggle(onlyContent) {
this.onlyContent = onlyContent
},
needShow(type, text) {
if (this.onlyContent && !text) {
return false
}
if (this.selectType === ALL) {
return true
} else {
return type === this.selectType
}
}
},
data() {
return {
ratings: [],
showFlag: false,
selectType: ALL,
onlyContent: false,
desc: {
all: '全部',
positive: '满意',
negative: '不满意'
}
}
}
子组件部分代码:
子元素通过props去接收父元素传来的数据,通过select和toggleContent函数去通知父元素改变数据
<div class="ratingselect">
<div class="rating-type border-1px">
<span class="block positive select" :class="{'active':selectType === 2}" @click="select(2, $event)">{{ desc.all }}<span class="count">{{ ratings.length }}</span></span>
<span class="block positive select" :class="{'active':selectType === 0}" @click="select(0, $event)">{{ desc.positive }}<span class="count">{{ positives.length }}</span></span>
<span class="block negative select" :class="{'active':selectType === 1}" @click="select(1, $event)">{{ desc.negative }}<span class="count">{{ negatives.length }}</span></span>
</div>
<div class="switch toggle" :class="{'on': onlyContent}" @click="toggleContent($event)">
<span class="icon-check_circle" ></span>
<span class="text">只看有内容的评价</span>
</div>
</div>
props: {
ratings: {
type: Array,
default() {
return []
}
},
selectType: {
type: Number,
default: ALL
},
onlyContent: {
type: Boolean,
default: false
},
desc: {
type: Object,
default() {
return {
all: '全部',
positive: '满意',
negative: '不满意'
}
}
}
},
computed: {
positives() {
return this.ratings.filter((rating) => {
return rating.rateType === POSITIVE
})
},
negatives() {
return this.ratings.filter((rating) => {
return rating.rateType === NEGATIVE
})
}
},
methods: {
select(type, event) {
if (!event._constructed) {
return false
}
this.$emit('select', type)
},
toggleContent(event) {
if (!event._constructed) {
return false
}
this.$emit('toggle', !this.onlyContent)
}
}
网友评论