如果未提供 url,则取消设置 img src vue.js



我正在学习vue.js 我正在测试它如何与 ajax 和 wp rest api 一起工作,我正在创建自定义面板主题,我想在可滚动面板中显示屏幕右侧的内容,在左侧显示页面。屏幕无法滚动。 我能够显示帖子和页面的内容,我还获得了特色图像,并将其放置在<img>标签中。我需要了解如何告诉 vue.js如果没有任何 url 数据来显示特色图像,则需要取消设置图像元素的 src。这可能吗?

<?php get_header(); ?>
<div class="container-fluid content-wrapper" style="overflow:hidden;height:100vh;">
<div class="row" id="app" style="margin:2em 0 2em 0;">
<!-- Sidebar Top Area -->
<div class="col-sm-12 col-md-4 col-lg-4" id="navPanel" style="padding:2em;">
<?php $links = new WP_Query( array('post_type' => 'page', 'posts_per_page' => -1) ); ?>
<?php if( $links->have_posts() ): while( $links->have_posts() ): $links->the_post(); ?>
<h1 class="home-claim" style="font-size:2em;">
<a class="" href="#" v-on:click.prevent="getContent(<?php echo get_the_ID(); ?>)" ><?php the_title(); ?></a>
</h1>
<?php endwhile; ?>
<?php endif; wp_reset_postdata(); ?>
</div>
<!-- Post/Pages Content -->
<div class="col-sm-12 col-md-8 col-lg-8" id="contentPanel" style="padding:0 0 2em 0;overflow:auto;height:100vh;">
<!-- Image here -->
<img class="img-fluid w-100" v-if="featuredImage" v-bind:src="featuredImage" />
<div class="" id="" v-html="content"></div>
</div>
<!-- Sidebar Bottom Area -->
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
(function($){
$(document).ready(function(){
var app = new Vue({
el: '#app',
data: {
content: null,
featuredImage: null,
},
mounted: function(){
},
methods: {
getContent: function(id){
console.log('method Fired!');
var self = this;
console.log(id);
var url = 'wp-json/wp/v2/pages/'+id+'?_embed';
$.getJSON( url, function(data){
console.log(data);
self.content = data.content.rendered;
self.featuredImage = data._embedded["wp:featuredmedia"][0].source_url;
//console.log(data._embedded["wp:featuredmedia"][0].source_url);
//console.log(data.content.rendered);
});
}
}
});
}); // doc ready
}(jQuery));
</script>
<?php get_footer(); ?>

我还注意到,仅对于我拥有的页面,wp api 才会返回特色图像的 401 代码。 任何帮助将不胜感激。

在执行加载之前取消设置特色图像:

(function($){
$(document).ready(function(){
var app = new Vue({
methods: {
getContent: function(id){
var self = this;
// unset the image before you are loading.
// this way it will also unset when the loading fails.
self.featuredImage = null;
var url = 'wp-json/wp/v2/pages/'+id+'?_embed';
$.getJSON( url, function(data){
self.featuredImage = data._embedded["wp:featuredmedia"][0].source_url;
});
}
}
});
});
}(jQuery));

最新更新