У меня два проблематика c проблем в Vue. js:
- Проблема фильтра:
Я хочу получить отфильтрованные записи моего API с помощью v-if. Я получаю свои записи, но не могу найти решение для их фильтрации.
Вопрос: Как мне отфильтровать статьи по выбранному параметру
in the <select v-model> <option>...</
Проблема с компонентами:
Каждый раз, когда я нажимаю кнопку на странице сведений о статье x, она просто отображает страницу детализации под домашней страницей. Я использую роутер, поэтому я использую роутер-ссылки, которые, очевидно, не работают соответственно
I cant use <router-link :to="/"> like that.
I after some searching i found i can use.
("' / '")
<router-link :to="'/'">
OR
<router-link to="/">
(without : and ' ')
Но я думаю, что маршрутизатор имеет меньшее отношение к визуализации компонентов друг под другом, даже когда я закомментировал страницу сведений. vue на домашней странице. vue. Кроме того, взгляните на мой код ниже:
Вопрос : Как убедиться, что компонент, к которому необходимо перейти, правильно открывается на другой странице?
homepage.vue
<template>
<div> <!-- You would have to wrap your list in another element (e.g., a div), making that the root: -->
<Menu/>
<div class="jumbotron">
<form>
<span><strong>Choose your sections below.</strong></span><br>
<div class="mt-3">
<select v-model="section">
<option v-bind:key="section.id" v-for="section in sections" :value="section" @clic="computed_items()">{{ section }}</option>
</select>
<div class="mt-3">Selected: <strong>{{ section }}</strong>
<div class="row mx-auto">
<div class="col-sm-12 col-md-6 col-lg-3 " v-bind:key="article.id" v-for="(article, index) in articles.slice(0,10)" > <!-- to get records you must loop within the div with the for -->
<div v-if="article.section == section" >
<b-card v-if="article.multimedia"
v-bind:title= "`${article.title}`"
v-bind:img-src="`${article.multimedia[0].url}`"
img-alt="Image"
img-top
tag="article"
style="max-width: 20rem;"
class="my-4"
>
<b-badge href="#" variant="dark">{{article.section}}</b-badge> <b-badge href="#" variant="light">{{article.subsection}}</b-badge>
<router-link :to="'/details'"></router-link>
<hr>
<b-card-text>
</b-card-text>
<b-button variant="primary" @click="goToDetails({index})"> More info </b-button><br>
</b-card>
</div>
<div v-else>
<p>{{article.subsection}} IS NOT {{section}}</p>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
<!-- <Details/> -->
<!-- <Details v-bind:details="details"/> -->
</div>
</template>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="lodash.js"></script>
<script>
//import Details from './Details.vue';
import Menu from './Menu.vue';
const SECTIONS = "home, arts, automobiles, books, business, fashion, food, health, insider, magazine, movies, national, nyregion, obituaries, opinion, politics, realestate, science, sports, sundayreview, technology, theater, tmagazine, travel, upshot, world"; // From NYTimes
console.log("000");
export default {
name: "Homepage",
components: {
//Details,
Menu
},
props: [
"articles"
],
methods: {
goToDetails(index){
this.$router.push(`/details/${index["index"]}`).catch(err => {});
console.log(index);
},
},
data(){
return{
selected: null,
sections: SECTIONS.split(','), //create an array of sections
section: 'home', // set default sections to ""home"""
}
}
}
</script>
Приложение. vue
<template>
<div id="app">
<Homepage v-bind:articles="articles" />
<Details v-bind:articles="articles" />
<router-view/>
</div>
</template>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
import Menu from './components/Menu.vue';
import Homepage from './components/Homepage.vue';
import Details from './components/Details.vue';
import Footer from './components/Footer.vue';
import axios from 'axios';
var url = 'https://api.nytimes.com/svc/topstories/v2/home.json?api-key=XXXX';
export default {
name: 'app',
components: {
Homepage,
Details,
Footer,
Menu
},
data(){
return {
articles: [], // empty array for the api records
}
},
created(){
axios.get(url)
//.then(res => this.movies = res.data)
//.then(res =>console.log(res.data['results']) )
.then(res => this.articles = res.data['results'])
// get the Records form the API use Vue detected tool extention via chrome.
}
}
</script>
index. html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
<title>vue_dtt_project_test</title>
</head>
<body>
<noscript>
<strong>We're sorry but vue_dtt_project_test doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
</noscript>
<div id="app"></div>
<!-- built files will be auto injected -->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://unpkg.com/vue@2.4.2"></script>
</body>
</html>
main. js
import Vue from 'vue';
import '@babel/polyfill';
import 'mutationobserver-shim';
import './plugins/bootstrap-vue';
import App from './App.vue';
import {router} from './routes';
import vSelect from 'vue-select';
import 'vue-select/dist/vue-select.css';
Vue.component('v-select', vSelect);
window.Vue = Vue;
Vue.config.productionTip = false;
window.Vue = require('vue');
//const routerz = new VueRouter({router});
new Vue({
router,
render: h => h(App),
}).$mount('#app');
router. js
// routes.js
import Vue from 'vue';
import VueRouter from 'vue-router';
import Homepage from './components/Homepage.vue';
import Details from './components/Details.vue';
import Footer from './components/Footer.vue';
//import router from './routes';
Vue.use(VueRouter);
//const router = new VueRouter({routes});
export const router = new VueRouter({
routes: [
{
path: '/',
name: 'homepage',
component: Homepage
},
{
path: '/details/:details_id',
name: 'details',
component: Details
},
{
path: '/footer',
name: 'footer',
component: Footer
}
]
});
Структура данных API
articles:Array[54]
0:Object
abstract:"The episode also brought to a head tensions in the U.S. attorney’s
office in Washington."
byline:"By Katie Benner, Charlie Savage, Sharon LaFraniere and Ben Protess"
created_date:"2020-02-12T21:25:28-05:00"
des_facet:Array[5]
geo_facet:Array[0]
item_type:"Article"
kicker:""
material_type_facet:""
multimedia:Array[5]
org_facet:Array[1]
per_facet:Array[5]
published_date:"2020-02-12T21:25:28-05:00"
section:"us"
subsection:"politics"
title:"After Stone Case, Prosecutors Say They Fear Pressure From Trump"
updated_date:"2020-02-13T09:48:45-05:00" stone-sentencing.html"
1:Object
2:Object
Заранее спасибо