当前,我正在将一些组件加载到一个较大的网格组件中(只是一个用于分组和显示子组件的组件)。
我要显示/隐藏一个按钮,具体取决于对象数据“ featureButtonLink”是否=“”。 (如果不相等,则显示按钮)。
问题是,我不确定切换v-if的逻辑应该在子组件上,还是在数组本身所在的“网格”组件上。
这是我的代码示例-
关于子组件:
<div v-if="link">
<h1>button here</h1>
</div>
<script>
export default {
name: 'FeatureWork',
props: [
'featureTitle', 'featureDescription', 'featureImage', 'featureClass', 'featureButtonLink', 'featureButtonText',
],
data () {
return {
link: false
}
},
computed: {
linkCheck: function() {
if (this.featured.id.featureButtonLink != '') {
this.link = true
return this.link
}
}
}
}
</script>
,这是我的“网格”组件(我在其中使用v-for +数组数据加载子组件的组件,该组件的内部值称为“ featureButtonLink”):
<template>
<div class="feature-work-row card-hover" :class="featureClass">
<div class="work-wrapper">
<!-- <div class="project-tags">
<p class="p-small text-weight-semi">Web Design</p>
<p class="p-small text-weight-semi">Web Design</p>
</div> -->
<div class="columns">
<div class="content">
<h4 class="text-weight-bold">{{ featureTitle }}</h4>
<p class="p-small text-color-regblue">{{ featureDescription }}</p>
<div class="button-container btn-main">
<router-link :to="featureButtonLink"><p class="p-small text-weight-semi">{{ featureButtonText }}</p></router-link>
</div>
<div v-if="link">
<h1>hey there</h1>
</div>
</div>
<div class="image">
<div class="image-wrapper">
<img :src="featureImage">
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
name: 'FeatureWork',
props: [
'featureTitle', 'featureDescription', 'featureImage', 'featureClass', 'featureButtonLink', 'featureButtonText',
],
data () {
return {
link: false
}
},
computed: {
linkCheck: function() {
if (this.featured.id.featureButtonLink != '') {
this.link = true
return this.link
}
}
}
}
</script>
或者,我想可能还有一个问题...
如何更改子组件的布尔值,该子组件与数据一起加载到该组件中。
我的子组件使用“父”组件上的数组加载到v-if中。 如何将数据“ true”传递回我的子组件,以决定是否在该按钮上显示(或不显示)按钮(使用v-if)。
答案 0 :(得分:0)
computed
的意义是要缓存数据,尽管您使用数据的方式也会要求调用它。
这是一些选项...
computed
按预期使用计算,返回值:
data () {
return {}
},
computed: {
link: function() {
return this.featured.id.featureButtonLink != '';
}
}
watch
data () {
return {
link: false
}
},
watch: {
featured:{
immediate: true
handler: function(val) {
if (val.id.featureButtonLink != '') {
this.link = true
return this.link
}
}
}
}
mounted
生命周期挂钩如果根据传递的prop值一次性渲染prop不变,则使用计算值几乎没有好处。相反,您可以只使用mounted
生命周期挂钩,这将使其仅在挂载时运行。这意味着它不会对值的更改做出反应,因此我将不显示示例。